Implemented the PoolCounter feature and did some general refactoring in the areas...
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 /**
3 * File for articles
4 * @file
5 */
6
7 /**
8 * Class representing a MediaWiki article and history.
9 *
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
13 *
14 */
15 class Article {
16 /**@{{
17 * @private
18 */
19 var $mComment = ''; //!<
20 var $mContent; //!<
21 var $mContentLoaded = false; //!<
22 var $mCounter = -1; //!< Not loaded
23 var $mCurID = -1; //!< Not loaded
24 var $mDataLoaded = false; //!<
25 var $mForUpdate = false; //!<
26 var $mGoodAdjustment = 0; //!<
27 var $mIsRedirect = false; //!<
28 var $mLatest = false; //!<
29 var $mMinorEdit; //!<
30 var $mOldId; //!<
31 var $mPreparedEdit = false; //!< Title object if set
32 var $mRedirectedFrom = null; //!< Title object if set
33 var $mRedirectTarget = null; //!< Title object if set
34 var $mRedirectUrl = false; //!<
35 var $mRevIdFetched = 0; //!<
36 var $mRevision; //!<
37 var $mTimestamp = ''; //!<
38 var $mTitle; //!<
39 var $mTotalAdjustment = 0; //!<
40 var $mTouched = '19700101000000'; //!<
41 var $mUser = -1; //!< Not loaded
42 var $mUserText = ''; //!<
43 var $mParserOptions; //!<
44 /**@}}*/
45
46 /**
47 * Constructor and clear the article
48 * @param $title Reference to a Title object.
49 * @param $oldId Integer revision ID, null to fetch from request, zero for current
50 */
51 public function __construct( Title $title, $oldId = null ) {
52 $this->mTitle =& $title;
53 $this->mOldId = $oldId;
54 }
55
56 /**
57 * Constructor from an article article
58 * @param $id The article ID to load
59 */
60 public static function newFromID( $id ) {
61 $t = Title::newFromID( $id );
62 return $t == null ? null : new Article( $t );
63 }
64
65 /**
66 * Tell the page view functions that this view was redirected
67 * from another page on the wiki.
68 * @param $from Title object.
69 */
70 public function setRedirectedFrom( $from ) {
71 $this->mRedirectedFrom = $from;
72 }
73
74 /**
75 * If this page is a redirect, get its target
76 *
77 * The target will be fetched from the redirect table if possible.
78 * If this page doesn't have an entry there, call insertRedirect()
79 * @return mixed Title object, or null if this page is not a redirect
80 */
81 public function getRedirectTarget() {
82 if( !$this->mTitle || !$this->mTitle->isRedirect() )
83 return null;
84 if( !is_null($this->mRedirectTarget) )
85 return $this->mRedirectTarget;
86 # Query the redirect table
87 $dbr = wfGetDB( DB_SLAVE );
88 $row = $dbr->selectRow( 'redirect',
89 array('rd_namespace', 'rd_title'),
90 array('rd_from' => $this->getID() ),
91 __METHOD__
92 );
93 if( $row ) {
94 return $this->mRedirectTarget = Title::makeTitle($row->rd_namespace, $row->rd_title);
95 }
96 # This page doesn't have an entry in the redirect table
97 return $this->mRedirectTarget = $this->insertRedirect();
98 }
99
100 /**
101 * Insert an entry for this page into the redirect table.
102 *
103 * Don't call this function directly unless you know what you're doing.
104 * @return Title object
105 */
106 public function insertRedirect() {
107 $retval = Title::newFromRedirect( $this->getContent() );
108 if( !$retval ) {
109 return null;
110 }
111 $dbw = wfGetDB( DB_MASTER );
112 $dbw->replace( 'redirect', array('rd_from'),
113 array(
114 'rd_from' => $this->getID(),
115 'rd_namespace' => $retval->getNamespace(),
116 'rd_title' => $retval->getDBkey()
117 ),
118 __METHOD__
119 );
120 return $retval;
121 }
122
123 /**
124 * Get the Title object this page redirects to
125 *
126 * @return mixed false, Title of in-wiki target, or string with URL
127 */
128 public function followRedirect() {
129 $text = $this->getContent();
130 return $this->followRedirectText( $text );
131 }
132
133 /**
134 * Get the Title object this text redirects to
135 *
136 * @return mixed false, Title of in-wiki target, or string with URL
137 */
138 public function followRedirectText( $text ) {
139 $rt = Title::newFromRedirectRecurse( $text ); // recurse through to only get the final target
140 # process if title object is valid and not special:userlogout
141 if( $rt ) {
142 if( $rt->getInterwiki() != '' ) {
143 if( $rt->isLocal() ) {
144 // Offsite wikis need an HTTP redirect.
145 //
146 // This can be hard to reverse and may produce loops,
147 // so they may be disabled in the site configuration.
148 $source = $this->mTitle->getFullURL( 'redirect=no' );
149 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
150 }
151 } else {
152 if( $rt->getNamespace() == NS_SPECIAL ) {
153 // Gotta handle redirects to special pages differently:
154 // Fill the HTTP response "Location" header and ignore
155 // the rest of the page we're on.
156 //
157 // This can be hard to reverse, so they may be disabled.
158 if( $rt->isSpecial( 'Userlogout' ) ) {
159 // rolleyes
160 } else {
161 return $rt->getFullURL();
162 }
163 }
164 return $rt;
165 }
166 }
167 // No or invalid redirect
168 return false;
169 }
170
171 /**
172 * get the title object of the article
173 */
174 public function getTitle() {
175 return $this->mTitle;
176 }
177
178 /**
179 * Clear the object
180 * @private
181 */
182 public function clear() {
183 $this->mDataLoaded = false;
184 $this->mContentLoaded = false;
185
186 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
187 $this->mRedirectedFrom = null; # Title object if set
188 $this->mRedirectTarget = null; # Title object if set
189 $this->mUserText =
190 $this->mTimestamp = $this->mComment = '';
191 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
192 $this->mTouched = '19700101000000';
193 $this->mForUpdate = false;
194 $this->mIsRedirect = false;
195 $this->mRevIdFetched = 0;
196 $this->mRedirectUrl = false;
197 $this->mLatest = false;
198 $this->mPreparedEdit = false;
199 }
200
201 /**
202 * Note that getContent/loadContent do not follow redirects anymore.
203 * If you need to fetch redirectable content easily, try
204 * the shortcut in Article::followContent()
205 *
206 * @return Return the text of this revision
207 */
208 public function getContent() {
209 global $wgUser, $wgContLang, $wgOut, $wgMessageCache;
210 wfProfileIn( __METHOD__ );
211 if( $this->getID() === 0 ) {
212 # If this is a MediaWiki:x message, then load the messages
213 # and return the message value for x.
214 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
215 # If this is a system message, get the default text.
216 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle->getText() ) );
217 $wgMessageCache->loadAllMessages( $lang );
218 $text = wfMsgGetKey( $message, false, $lang, false );
219 if( wfEmptyMsg( $message, $text ) )
220 $text = '';
221 } else {
222 $text = wfMsgExt( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon', 'parsemag' );
223 }
224 wfProfileOut( __METHOD__ );
225 return $text;
226 } else {
227 $this->loadContent();
228 wfProfileOut( __METHOD__ );
229 return $this->mContent;
230 }
231 }
232
233 /**
234 * Get the text of the current revision. No side-effects...
235 *
236 * @return Return the text of the current revision
237 */
238 public function getRawText() {
239 // Check process cache for current revision
240 if( $this->mContentLoaded && $this->mOldId == 0 ) {
241 return $this->mContent;
242 }
243 $rev = Revision::newFromTitle( $this->mTitle );
244 $text = $rev ? $rev->getRawText() : false;
245 return $text;
246 }
247
248 /**
249 * This function returns the text of a section, specified by a number ($section).
250 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
251 * the first section before any such heading (section 0).
252 *
253 * If a section contains subsections, these are also returned.
254 *
255 * @param $text String: text to look in
256 * @param $section Integer: section number
257 * @return string text of the requested section
258 * @deprecated
259 */
260 public function getSection( $text, $section ) {
261 global $wgParser;
262 return $wgParser->getSection( $text, $section );
263 }
264
265 /**
266 * Get the text that needs to be saved in order to undo all revisions
267 * between $undo and $undoafter. Revisions must belong to the same page,
268 * must exist and must not be deleted
269 * @param $undo Revision
270 * @param $undoafter Revision Must be an earlier revision than $undo
271 * @return mixed string on success, false on failure
272 */
273 public function getUndoText( Revision $undo, Revision $undoafter = null ) {
274 $undo_text = $undo->getText();
275 $undoafter_text = $undoafter->getText();
276 $cur_text = $this->getContent();
277 if ( $cur_text == $undo_text ) {
278 # No use doing a merge if it's just a straight revert.
279 return $undoafter_text;
280 }
281 $undone_text = '';
282 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) )
283 return false;
284 return $undone_text;
285 }
286
287 /**
288 * @return int The oldid of the article that is to be shown, 0 for the
289 * current revision
290 */
291 public function getOldID() {
292 if( is_null( $this->mOldId ) ) {
293 $this->mOldId = $this->getOldIDFromRequest();
294 }
295 return $this->mOldId;
296 }
297
298 /**
299 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
300 *
301 * @return int The old id for the request
302 */
303 public function getOldIDFromRequest() {
304 global $wgRequest;
305 $this->mRedirectUrl = false;
306 $oldid = $wgRequest->getVal( 'oldid' );
307 if( isset( $oldid ) ) {
308 $oldid = intval( $oldid );
309 if( $wgRequest->getVal( 'direction' ) == 'next' ) {
310 $nextid = $this->mTitle->getNextRevisionID( $oldid );
311 if( $nextid ) {
312 $oldid = $nextid;
313 } else {
314 $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
315 }
316 } elseif( $wgRequest->getVal( 'direction' ) == 'prev' ) {
317 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
318 if( $previd ) {
319 $oldid = $previd;
320 }
321 }
322 }
323 if( !$oldid ) {
324 $oldid = 0;
325 }
326 return $oldid;
327 }
328
329 /**
330 * Load the revision (including text) into this object
331 */
332 function loadContent() {
333 if( $this->mContentLoaded ) return;
334 wfProfileIn( __METHOD__ );
335 # Query variables :P
336 $oldid = $this->getOldID();
337 # Pre-fill content with error message so that if something
338 # fails we'll have something telling us what we intended.
339 $this->mOldId = $oldid;
340 $this->fetchContent( $oldid );
341 wfProfileOut( __METHOD__ );
342 }
343
344
345 /**
346 * Fetch a page record with the given conditions
347 * @param $dbr Database object
348 * @param $conditions Array
349 */
350 protected function pageData( $dbr, $conditions ) {
351 $fields = array(
352 'page_id',
353 'page_namespace',
354 'page_title',
355 'page_restrictions',
356 'page_counter',
357 'page_is_redirect',
358 'page_is_new',
359 'page_random',
360 'page_touched',
361 'page_latest',
362 'page_len',
363 );
364 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
365 $row = $dbr->selectRow(
366 'page',
367 $fields,
368 $conditions,
369 __METHOD__
370 );
371 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
372 return $row ;
373 }
374
375 /**
376 * @param $dbr Database object
377 * @param $title Title object
378 */
379 public function pageDataFromTitle( $dbr, $title ) {
380 return $this->pageData( $dbr, array(
381 'page_namespace' => $title->getNamespace(),
382 'page_title' => $title->getDBkey() ) );
383 }
384
385 /**
386 * @param $dbr Database
387 * @param $id Integer
388 */
389 protected function pageDataFromId( $dbr, $id ) {
390 return $this->pageData( $dbr, array( 'page_id' => $id ) );
391 }
392
393 /**
394 * Set the general counter, title etc data loaded from
395 * some source.
396 *
397 * @param $data Database row object or "fromdb"
398 */
399 public function loadPageData( $data = 'fromdb' ) {
400 if( $data === 'fromdb' ) {
401 $dbr = wfGetDB( DB_MASTER );
402 $data = $this->pageDataFromId( $dbr, $this->getId() );
403 }
404
405 $lc = LinkCache::singleton();
406 if( $data ) {
407 $lc->addGoodLinkObj( $data->page_id, $this->mTitle, $data->page_len, $data->page_is_redirect );
408
409 $this->mTitle->mArticleID = $data->page_id;
410
411 # Old-fashioned restrictions
412 $this->mTitle->loadRestrictions( $data->page_restrictions );
413
414 $this->mCounter = $data->page_counter;
415 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
416 $this->mIsRedirect = $data->page_is_redirect;
417 $this->mLatest = $data->page_latest;
418 } else {
419 if( is_object( $this->mTitle ) ) {
420 $lc->addBadLinkObj( $this->mTitle );
421 }
422 $this->mTitle->mArticleID = 0;
423 }
424
425 $this->mDataLoaded = true;
426 }
427
428 /**
429 * Get text of an article from database
430 * Does *NOT* follow redirects.
431 * @param $oldid Int: 0 for whatever the latest revision is
432 * @return string
433 */
434 function fetchContent( $oldid = 0 ) {
435 if( $this->mContentLoaded ) {
436 return $this->mContent;
437 }
438
439 $dbr = wfGetDB( DB_MASTER );
440
441 # Pre-fill content with error message so that if something
442 # fails we'll have something telling us what we intended.
443 $t = $this->mTitle->getPrefixedText();
444 $d = $oldid ? wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
445 $this->mContent = wfMsg( 'missing-article', $t, $d ) ;
446
447 if( $oldid ) {
448 $revision = Revision::newFromId( $oldid );
449 if( is_null( $revision ) ) {
450 wfDebug( __METHOD__." failed to retrieve specified revision, id $oldid\n" );
451 return false;
452 }
453 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
454 if( !$data ) {
455 wfDebug( __METHOD__." failed to get page data linked to revision id $oldid\n" );
456 return false;
457 }
458 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
459 $this->loadPageData( $data );
460 } else {
461 if( !$this->mDataLoaded ) {
462 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
463 if( !$data ) {
464 wfDebug( __METHOD__." failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
465 return false;
466 }
467 $this->loadPageData( $data );
468 }
469 $revision = Revision::newFromId( $this->mLatest );
470 if( is_null( $revision ) ) {
471 wfDebug( __METHOD__." failed to retrieve current page, rev_id {$this->mLatest}\n" );
472 return false;
473 }
474 }
475
476 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
477 // We should instead work with the Revision object when we need it...
478 $this->mContent = $revision->getText( Revision::FOR_THIS_USER ); // Loads if user is allowed
479
480 $this->mUser = $revision->getUser();
481 $this->mUserText = $revision->getUserText();
482 $this->mComment = $revision->getComment();
483 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
484
485 $this->mRevIdFetched = $revision->getId();
486 $this->mContentLoaded = true;
487 $this->mRevision =& $revision;
488
489 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
490
491 return $this->mContent;
492 }
493
494 /**
495 * Read/write accessor to select FOR UPDATE
496 *
497 * @param $x Mixed: FIXME
498 */
499 public function forUpdate( $x = NULL ) {
500 return wfSetVar( $this->mForUpdate, $x );
501 }
502
503 /**
504 * Get the database which should be used for reads
505 *
506 * @return Database
507 * @deprecated - just call wfGetDB( DB_MASTER ) instead
508 */
509 function getDB() {
510 wfDeprecated( __METHOD__ );
511 return wfGetDB( DB_MASTER );
512 }
513
514 /**
515 * Get options for all SELECT statements
516 *
517 * @param $options Array: an optional options array which'll be appended to
518 * the default
519 * @return Array: options
520 */
521 protected function getSelectOptions( $options = '' ) {
522 if( $this->mForUpdate ) {
523 if( is_array( $options ) ) {
524 $options[] = 'FOR UPDATE';
525 } else {
526 $options = 'FOR UPDATE';
527 }
528 }
529 return $options;
530 }
531
532 /**
533 * @return int Page ID
534 */
535 public function getID() {
536 if( $this->mTitle ) {
537 return $this->mTitle->getArticleID();
538 } else {
539 return 0;
540 }
541 }
542
543 /**
544 * @return bool Whether or not the page exists in the database
545 */
546 public function exists() {
547 return $this->getId() > 0;
548 }
549
550 /**
551 * Check if this page is something we're going to be showing
552 * some sort of sensible content for. If we return false, page
553 * views (plain action=view) will return an HTTP 404 response,
554 * so spiders and robots can know they're following a bad link.
555 *
556 * @return bool
557 */
558 public function hasViewableContent() {
559 return $this->exists() || $this->mTitle->isAlwaysKnown();
560 }
561
562 /**
563 * @return int The view count for the page
564 */
565 public function getCount() {
566 if( -1 == $this->mCounter ) {
567 $id = $this->getID();
568 if( $id == 0 ) {
569 $this->mCounter = 0;
570 } else {
571 $dbr = wfGetDB( DB_SLAVE );
572 $this->mCounter = $dbr->selectField( 'page',
573 'page_counter',
574 array( 'page_id' => $id ),
575 __METHOD__,
576 $this->getSelectOptions()
577 );
578 }
579 }
580 return $this->mCounter;
581 }
582
583 /**
584 * Determine whether a page would be suitable for being counted as an
585 * article in the site_stats table based on the title & its content
586 *
587 * @param $text String: text to analyze
588 * @return bool
589 */
590 public function isCountable( $text ) {
591 global $wgUseCommaCount;
592
593 $token = $wgUseCommaCount ? ',' : '[[';
594 return $this->mTitle->isContentPage() && !$this->isRedirect($text) && in_string($token,$text);
595 }
596
597 /**
598 * Tests if the article text represents a redirect
599 *
600 * @param $text String: FIXME
601 * @return bool
602 */
603 public function isRedirect( $text = false ) {
604 if( $text === false ) {
605 if( $this->mDataLoaded ) {
606 return $this->mIsRedirect;
607 }
608 // Apparently loadPageData was never called
609 $this->loadContent();
610 $titleObj = Title::newFromRedirectRecurse( $this->fetchContent() );
611 } else {
612 $titleObj = Title::newFromRedirect( $text );
613 }
614 return $titleObj !== NULL;
615 }
616
617 /**
618 * Returns true if the currently-referenced revision is the current edit
619 * to this page (and it exists).
620 * @return bool
621 */
622 public function isCurrent() {
623 # If no oldid, this is the current version.
624 if( $this->getOldID() == 0 ) {
625 return true;
626 }
627 return $this->exists() && isset($this->mRevision) && $this->mRevision->isCurrent();
628 }
629
630 /**
631 * Loads everything except the text
632 * This isn't necessary for all uses, so it's only done if needed.
633 */
634 protected function loadLastEdit() {
635 if( -1 != $this->mUser )
636 return;
637
638 # New or non-existent articles have no user information
639 $id = $this->getID();
640 if( 0 == $id ) return;
641
642 $this->mLastRevision = Revision::loadFromPageId( wfGetDB( DB_MASTER ), $id );
643 if( !is_null( $this->mLastRevision ) ) {
644 $this->mUser = $this->mLastRevision->getUser();
645 $this->mUserText = $this->mLastRevision->getUserText();
646 $this->mTimestamp = $this->mLastRevision->getTimestamp();
647 $this->mComment = $this->mLastRevision->getComment();
648 $this->mMinorEdit = $this->mLastRevision->isMinor();
649 $this->mRevIdFetched = $this->mLastRevision->getId();
650 }
651 }
652
653 public function getTimestamp() {
654 // Check if the field has been filled by ParserCache::get()
655 if( !$this->mTimestamp ) {
656 $this->loadLastEdit();
657 }
658 return wfTimestamp(TS_MW, $this->mTimestamp);
659 }
660
661 public function getUser() {
662 $this->loadLastEdit();
663 return $this->mUser;
664 }
665
666 public function getUserText() {
667 $this->loadLastEdit();
668 return $this->mUserText;
669 }
670
671 public function getComment() {
672 $this->loadLastEdit();
673 return $this->mComment;
674 }
675
676 public function getMinorEdit() {
677 $this->loadLastEdit();
678 return $this->mMinorEdit;
679 }
680
681 /* Use this to fetch the rev ID used on page views */
682 public function getRevIdFetched() {
683 $this->loadLastEdit();
684 return $this->mRevIdFetched;
685 }
686
687 /**
688 * @param $limit Integer: default 0.
689 * @param $offset Integer: default 0.
690 */
691 public function getContributors($limit = 0, $offset = 0) {
692 # XXX: this is expensive; cache this info somewhere.
693
694 $contribs = array();
695 $dbr = wfGetDB( DB_SLAVE );
696 $revTable = $dbr->tableName( 'revision' );
697 $userTable = $dbr->tableName( 'user' );
698 $user = $this->getUser();
699 $pageId = $this->getId();
700
701 $deletedBit = $dbr->bitAnd('rev_deleted', Revision::DELETED_USER); // username hidden?
702
703 $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp
704 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
705 WHERE rev_page = $pageId
706 AND rev_user != $user
707 AND $deletedBit = 0
708 GROUP BY rev_user, rev_user_text, user_real_name
709 ORDER BY timestamp DESC";
710
711 if($limit > 0)
712 $sql = $dbr->limitResult($sql, $limit, $offset);
713
714 $sql .= ' '. $this->getSelectOptions();
715
716 $res = $dbr->query($sql, __METHOD__ );
717
718 return new UserArrayFromResult( $res );
719 }
720
721 /**
722 * This is the default action of the index.php entry point: just view the
723 * page of the given title.
724 */
725 public function view() {
726 global $wgUser, $wgOut, $wgRequest, $wgContLang;
727 global $wgEnableParserCache, $wgStylePath, $wgParser;
728 global $wgUseTrackbacks;
729
730 wfProfileIn( __METHOD__ );
731
732 # Get variables from query string
733 $oldid = $this->getOldID();
734 $parserCache = ParserCache::singleton();
735
736 $parserOptions = clone $this->getParserOptions();
737 # Render printable version, use printable version cache
738 if ( $wgOut->isPrintable() ) {
739 $parserOptions->setIsPrintable( true );
740 }
741
742 # Try client and file cache
743 if( $oldid === 0 && $this->checkTouched() ) {
744 global $wgUseETag;
745 if( $wgUseETag ) {
746 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
747 }
748 # Is is client cached?
749 if( $wgOut->checkLastModified( $this->getTouched() ) ) {
750 wfDebug( __METHOD__.": done 304\n" );
751 wfProfileOut( __METHOD__ );
752 return;
753 # Try file cache
754 } else if( $this->tryFileCache() ) {
755 wfDebug( __METHOD__.": done file cache\n" );
756 # tell wgOut that output is taken care of
757 $wgOut->disable();
758 $this->viewUpdates();
759 wfProfileOut( __METHOD__ );
760 return;
761 }
762 }
763
764 $sk = $wgUser->getSkin();
765
766 # getOldID may want us to redirect somewhere else
767 if( $this->mRedirectUrl ) {
768 $wgOut->redirect( $this->mRedirectUrl );
769 wfDebug( __METHOD__.": redirecting due to oldid\n" );
770 wfProfileOut( __METHOD__ );
771 return;
772 }
773
774 $wgOut->setArticleFlag( true );
775 $wgOut->setRobotPolicy( $this->getRobotPolicyForView() );
776 # Set page title (may be overridden by DISPLAYTITLE)
777 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
778
779 # If we got diff in the query, we want to see a diff page instead of the article.
780 if( !is_null( $wgRequest->getVal( 'diff' ) ) ) {
781 wfDebug( __METHOD__.": showing diff page\n" );
782 $this->showDiffPage();
783 wfProfileOut( __METHOD__ );
784 return;
785 }
786
787 # Should the parser cache be used?
788 $useParserCache = $this->useParserCache( $oldid );
789 wfDebug( 'Article::view using parser cache: ' . ($useParserCache ? 'yes' : 'no' ) . "\n" );
790 if( $wgUser->getOption( 'stubthreshold' ) ) {
791 wfIncrStats( 'pcache_miss_stub' );
792 }
793
794 # For the main page, overwrite the <title> element with the con-
795 # tents of 'pagetitle-view-mainpage' instead of the default (if
796 # that's not empty).
797 if( $this->mTitle->equals( Title::newMainPage() )
798 && wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' )
799 {
800 $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) );
801 }
802
803 $wasRedirected = $this->showRedirectedFromHeader();
804 $this->showNamespaceHeader();
805
806 $outputDone = false;
807 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
808
809 # Try the parser cache
810 if( !$outputDone && $useParserCache ) {
811 $parserOutput = $parserCache->get( $this, $parserOptions );
812 if ( $parserOutput !== false ) {
813 wfDebug( __METHOD__.": showing parser cache contents\n" );
814 $wgOut->addParserOutput( $parserOutput );
815 // Ensure that UI elements requiring revision ID have
816 // the correct version information.
817 $wgOut->setRevisionId( $this->mLatest );
818 $outputDone = true;
819 }
820 }
821
822 if ( $outputDone ) {
823 $this->showViewFooter();
824 $this->viewUpdates();
825 wfProfileOut( __METHOD__ );
826 return;
827 }
828
829 $text = $this->getContent();
830 if( $text === false || $this->getID() == 0 ) {
831 wfDebug( __METHOD__.": showing missing article\n" );
832 $this->showMissingArticle();
833 wfProfileOut( __METHOD__ );
834 return;
835 }
836
837 # Another whitelist check in case oldid is altering the title
838 if( !$this->mTitle->userCanRead() ) {
839 wfDebug( __METHOD__.": denied on secondary read check\n" );
840 $wgOut->loginToUse();
841 $wgOut->output();
842 $wgOut->disable();
843 wfProfileOut( __METHOD__ );
844 return;
845 }
846
847 # We're looking at an old revision
848 if( $oldid && !is_null( $this->mRevision ) ) {
849 $this->setOldSubtitle( $oldid );
850 if ( !$this->showDeletedRevisionHeader() ) {
851 wfDebug( __METHOD__.": cannot view deleted revision\n" );
852 wfProfileOut( __METHOD__ );
853 return;
854 }
855
856 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
857 $parserOutput = $parserCache->get( $this, $parserOptions );
858 if ( $parserOutput ) {
859 wfDebug( __METHOD__.": showing parser cache for current rev permalink\n" );
860 $wgOut->addParserOutput( $parserOutput );
861 $this->showViewFooter();
862 $this->viewUpdates();
863 wfProfileOut( __METHOD__ );
864 return;
865 }
866 }
867 }
868
869 // Ensure that UI elements requiring revision ID have
870 // the correct version information.
871 $wgOut->setRevisionId( $this->getRevIdFetched() );
872
873 // Pages containing custom CSS or JavaScript get special treatment
874 if( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
875 wfDebug( __METHOD__.": showing CSS/JS source\n" );
876 $this->showCssOrJsPage();
877 $outputDone = true;
878 } else if( $rt = Title::newFromRedirectArray( $text ) ) {
879 wfDebug( __METHOD__.": showing redirect=no page\n" );
880 # Viewing a redirect page (e.g. with parameter redirect=no)
881 # Don't append the subtitle if this was an old revision
882 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
883 # Parse just to get categories, displaytitle, etc.
884 $parserOutput = $wgParser->parse( $text, $this->mTitle, $parserOptions );
885 $wgOut->addParserOutputNoText( $parserOutput );
886 $outputDone = true;
887 }
888 if ( $outputDone ) {
889 $this->showViewFooter();
890 $this->viewUpdates();
891 wfProfileOut( __METHOD__ );
892 return;
893 }
894
895 # Run the parse, protected by a pool counter
896 wfDebug( __METHOD__.": doing uncached parse\n" );
897 $key = $parserCache->getKey( $this, $parserOptions );
898 $poolCounter = PoolCounter::factory( 'Article::view', $key );
899 $dirtyCallback = $useParserCache ? array( $this, 'tryDirtyCache' ) : false;
900 $status = $poolCounter->executeProtected( array( $this, 'doViewParse' ), $dirtyCallback );
901
902 if ( !$status->isOK() ) {
903 # Connection or timeout error
904 $this->showPoolError( $status );
905 wfProfileOut( __METHOD__ );
906 return;
907 }
908
909 $this->showViewFooter();
910 $this->viewUpdates();
911 wfProfileOut( __METHOD__ );
912 }
913
914 /**
915 * Show a diff page according to current request variables. For use within
916 * Article::view() only, other callers should use the DifferenceEngine class.
917 */
918 public function showDiffPage() {
919 global $wgOut, $wgRequest, $wgUser;
920
921 $diff = $wgRequest->getVal( 'diff' );
922 $rcid = $wgRequest->getVal( 'rcid' );
923 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
924 $purge = $wgRequest->getVal( 'action' ) == 'purge';
925 $htmldiff = $wgRequest->getVal( 'htmldiff' , false);
926 $unhide = $wgRequest->getInt('unhide') == 1;
927 $oldid = $this->getOldID();
928
929 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge, $htmldiff, $unhide );
930 // DifferenceEngine directly fetched the revision:
931 $this->mRevIdFetched = $de->mNewid;
932 $de->showDiffPage( $diffOnly );
933
934 // Needed to get the page's current revision
935 $this->loadPageData();
936 if( $diff == 0 || $diff == $this->mLatest ) {
937 # Run view updates for current revision only
938 $this->viewUpdates();
939 }
940 }
941
942 /**
943 * Show a page view for a page formatted as CSS or JavaScript. To be called by
944 * Article::view() only.
945 *
946 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
947 * page views.
948 */
949 public function showCssOrJsPage() {
950 global $wgOut;
951 $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
952 // Give hooks a chance to customise the output
953 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
954 // Wrap the whole lot in a <pre> and don't parse
955 $m = array();
956 preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
957 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
958 $wgOut->addHTML( htmlspecialchars( $this->mContent ) );
959 $wgOut->addHTML( "\n</pre>\n" );
960 }
961 }
962
963 /**
964 * Get the robot policy to be used for the current action=view request.
965 */
966 public function getRobotPolicyForView() {
967 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
968 global $wgDefaultRobotPolicy, $wgRequest;
969
970 $ns = $this->mTitle->getNamespace();
971 if( $ns == NS_USER || $ns == NS_USER_TALK ) {
972 # Don't index user and user talk pages for blocked users (bug 11443)
973 if( !$this->mTitle->isSubpage() ) {
974 $block = new Block();
975 if( $block->load( $this->mTitle->getText() ) ) {
976 return 'noindex,nofollow';
977 }
978 }
979 }
980
981 if( $this->getID() === 0 || $this->getOldID() ) {
982 return 'noindex,nofollow';
983 } elseif( $wgOut->isPrintable() ) {
984 # Discourage indexing of printable versions, but encourage following
985 return 'noindex,follow';
986 } elseif( $wgRequest->getInt('curid') ) {
987 # For ?curid=x urls, disallow indexing
988 return 'noindex,follow';
989 } elseif( isset( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) ) {
990 return $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()];
991 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
992 # Honour customised robot policies for this namespace
993 return $wgNamespaceRobotPolicies[$ns];
994 } else {
995 return $wgDefaultRobotPolicy;
996 }
997 }
998
999 /**
1000 * If this request is a redirect view, send "redirected from" subtitle to
1001 * $wgOut. Returns true if the header was needed, false if this is not a
1002 * redirect view. Handles both local and remote redirects.
1003 */
1004 public function showRedirectedFromHeader() {
1005 global $wgOut, $wgUser, $wgRequest, $wgRedirectSources;
1006
1007 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1008 $sk = $wgUser->getSkin();
1009 if( isset( $this->mRedirectedFrom ) ) {
1010 // This is an internally redirected page view.
1011 // We'll need a backlink to the source page for navigation.
1012 if( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1013 $redir = $sk->link(
1014 $this->mRedirectedFrom,
1015 null,
1016 array(),
1017 array( 'redirect' => 'no' ),
1018 array( 'known', 'noclasses' )
1019 );
1020 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1021 $wgOut->setSubtitle( $s );
1022
1023 // Set the fragment if one was specified in the redirect
1024 if( strval( $this->mTitle->getFragment() ) != '' ) {
1025 $fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() );
1026 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1027 }
1028
1029 // Add a <link rel="canonical"> tag
1030 $wgOut->addLink( array( 'rel' => 'canonical',
1031 'href' => $this->mTitle->getLocalURL() )
1032 );
1033 return true;
1034 }
1035 } elseif( $rdfrom ) {
1036 // This is an externally redirected view, from some other wiki.
1037 // If it was reported from a trusted site, supply a backlink.
1038 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1039 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
1040 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1041 $wgOut->setSubtitle( $s );
1042 return true;
1043 }
1044 }
1045 return false;
1046 }
1047
1048 /**
1049 * Show a header specific to the namespace currently being viewed, like
1050 * [[MediaWiki:Talkpagetext]]. For Article::view().
1051 */
1052 public function showNamespaceHeader() {
1053 global $wgOut;
1054 if( $this->mTitle->isTalkPage() ) {
1055 $msg = wfMsgNoTrans( 'talkpageheader' );
1056 if ( $msg !== '-' && !wfEmptyMsg( 'talkpageheader', $msg ) ) {
1057 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1</div>", array( 'talkpageheader' ) );
1058 }
1059 }
1060 }
1061
1062 /**
1063 * Show the footer section of an ordinary page view
1064 */
1065 public function showViewFooter() {
1066 global $wgOut, $wgUseTrackbacks, $wgRequest;
1067 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1068 if( $this->mTitle->getNamespace() == NS_USER_TALK && IP::isValid( $this->mTitle->getText() ) ) {
1069 $wgOut->addWikiMsg('anontalkpagetext');
1070 }
1071
1072 # If we have been passed an &rcid= parameter, we want to give the user a
1073 # chance to mark this new article as patrolled.
1074 $this->showPatrolFooter();
1075
1076 # Trackbacks
1077 if( $wgUseTrackbacks ) {
1078 $this->addTrackbacks();
1079 }
1080 }
1081
1082 /**
1083 * If patrol is possible, output a patrol UI box. This is called from the
1084 * footer section of ordinary page views. If patrol is not possible or not
1085 * desired, does nothing.
1086 */
1087 public function showPatrolFooter() {
1088 global $wgOut, $wgRequest;
1089 $rcid = $wgRequest->getVal( 'rcid' );
1090
1091 if( !$rcid || !$this->mTitle->exists() || !$this->mTitle->quickUserCan( 'patrol' ) ) {
1092 return;
1093 }
1094
1095 $wgOut->addHTML(
1096 "<div class='patrollink'>" .
1097 wfMsgHtml(
1098 'markaspatrolledlink',
1099 $sk->link(
1100 $this->mTitle,
1101 wfMsgHtml( 'markaspatrolledtext' ),
1102 array(),
1103 array(
1104 'action' => 'markpatrolled',
1105 'rcid' => $rcid
1106 ),
1107 array( 'known', 'noclasses' )
1108 )
1109 ) .
1110 '</div>'
1111 );
1112 }
1113
1114 /**
1115 * Show the error text for a missing article. For articles in the MediaWiki
1116 * namespace, show the default message text. To be called from Article::view().
1117 */
1118 public function showMissingArticle() {
1119 global $wgOut, $wgRequest;
1120 # Show delete and move logs
1121 $this->showLogs();
1122
1123 # Show error message
1124 $oldid = $this->getOldID();
1125 if( $oldid ) {
1126 $text = wfMsgNoTrans( 'missing-article',
1127 $this->mTitle->getPrefixedText(),
1128 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1129 } elseif ( $this->mTitle->getNamespace() === NS_MEDIAWIKI ) {
1130 // Use the default message text
1131 $text = $this->getContent();
1132 } else {
1133 $text = wfMsgNoTrans( 'noarticletext' );
1134 }
1135 $text = "<div class='noarticletext'>\n$text\n</div>";
1136 if( !$this->hasViewableContent() ) {
1137 // If there's no backing content, send a 404 Not Found
1138 // for better machine handling of broken links.
1139 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
1140 }
1141 $wgOut->addWikiText( $text );
1142 }
1143
1144 /**
1145 * If the revision requested for view is deleted, check permissions.
1146 * Send either an error message or a warning header to $wgOut.
1147 * Returns true if the view is allowed, false if not.
1148 */
1149 public function showDeletedRevisionHeader() {
1150 global $wgOut, $wgRequest;
1151
1152 if( !$this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1153 // Not deleted
1154 return true;
1155 }
1156
1157 // If the user is not allowed to see it...
1158 if( !$this->mRevision->userCan(Revision::DELETED_TEXT) ) {
1159 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1160 'rev-deleted-text-permission' );
1161 return false;
1162 // If the user needs to confirm that they want to see it...
1163 } else if( $wgRequest->getInt('unhide') != 1 ) {
1164 # Give explanation and add a link to view the revision...
1165 $oldid = intval( $this->getOldID() );
1166 $link = $this->mTitle->getFullUrl( "oldid={$oldid}&unhide=1" );
1167 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1168 array('rev-deleted-text-unhide',$link) );
1169 return false;
1170 // We are allowed to see...
1171 } else {
1172 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1173 'rev-deleted-text-view' );
1174 return true;
1175 }
1176 }
1177
1178 /**
1179 * Show an excerpt from the deletion and move logs. To be called from the
1180 * header section on page views of missing pages.
1181 */
1182 public function showLogs() {
1183 global $wgUser, $wgOut;
1184 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
1185 $pager = new LogPager( $loglist, array('move', 'delete'), false,
1186 $this->mTitle->getPrefixedText(), '', array( "log_action != 'revision'" ) );
1187 if( $pager->getNumRows() > 0 ) {
1188 $pager->mLimit = 10;
1189 $wgOut->addHTML( '<div class="mw-warning-with-logexcerpt">' );
1190 $wgOut->addWikiMsg( 'moveddeleted-notice' );
1191 $wgOut->addHTML(
1192 $loglist->beginLogEventsList() .
1193 $pager->getBody() .
1194 $loglist->endLogEventsList()
1195 );
1196 if( $pager->getNumRows() > 10 ) {
1197 $wgOut->addHTML( $wgUser->getSkin()->link(
1198 SpecialPage::getTitleFor( 'Log' ),
1199 wfMsgHtml( 'log-fulllog' ),
1200 array(),
1201 array( 'page' => $this->mTitle->getPrefixedText() )
1202 ) );
1203 }
1204 $wgOut->addHTML( '</div>' );
1205 }
1206 }
1207
1208 /*
1209 * Should the parser cache be used?
1210 */
1211 public function useParserCache( $oldid ) {
1212 global $wgUser, $wgEnableParserCache;
1213
1214 return $wgEnableParserCache
1215 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
1216 && $this->exists()
1217 && empty( $oldid )
1218 && !$this->mTitle->isCssOrJsPage()
1219 && !$this->mTitle->isCssJsSubpage();
1220 }
1221
1222 /**
1223 * Execute the uncached parse for action=view
1224 */
1225 public function doViewParse() {
1226 global $wgOut;
1227 $oldid = $this->getOldID();
1228 $useParserCache = $this->useParserCache( $oldid );
1229 $parserOptions = clone $this->getParserOptions();
1230 # Render printable version, use printable version cache
1231 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1232 # Don't show section-edit links on old revisions... this way lies madness.
1233 $parserOptions->setEditSection( $this->isCurrent() );
1234 $useParserCache = $this->useParserCache( $oldid );
1235 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1236 }
1237
1238 /**
1239 * Try to fetch an expired entry from the parser cache. If it is present,
1240 * output it and return true. If it is not present, output nothing and
1241 * return false. This is used as a callback function for
1242 * PoolCounter::executeProtected().
1243 */
1244 public function tryDirtyCache() {
1245 global $wgOut;
1246 $parserCache = ParserCache::singleton();
1247 $options = $this->getParserOptions();
1248 $options->setIsPrintable( $wgOut->isPrintable() );
1249 $output = $parserCache->getDirty( $this, $options );
1250 if ( $output ) {
1251 wfDebug( __METHOD__.": sending dirty output\n" );
1252 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1253 $wgOut->setSquidMaxage( 0 );
1254 $wgOut->addParserOutput( $output );
1255 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1256 return true;
1257 } else {
1258 wfDebugLog( 'dirty', "dirty missing\n" );
1259 wfDebug( __METHOD__.": no dirty cache\n" );
1260 return false;
1261 }
1262 }
1263
1264 /**
1265 * Show an error page for an error from the pool counter.
1266 * @param $status Status
1267 */
1268 public function showPoolError( $status ) {
1269 global $wgOut;
1270 $wgOut->clearHTML(); // for release() errors
1271 $wgOut->enableClientCache( false );
1272 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1273 $wgOut->addWikiText(
1274 '<div class="errorbox">' .
1275 $status->getWikiText( false, 'view-pool-error' ) .
1276 '</div>'
1277 );
1278 }
1279
1280 /**
1281 * View redirect
1282 * @param $target Title object or Array of destination(s) to redirect
1283 * @param $appendSubtitle Boolean [optional]
1284 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1285 */
1286 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1287 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
1288 # Display redirect
1289 if( !is_array( $target ) ) {
1290 $target = array( $target );
1291 }
1292 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
1293 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1294 $imageUrl2 = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1295 $alt2 = $wgContLang->isRTL() ? '&larr;' : '&rarr;'; // should -> and <- be used instead of entities?
1296
1297 if( $appendSubtitle ) {
1298 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1299 }
1300 $sk = $wgUser->getSkin();
1301 // the loop prepends the arrow image before the link, so the first case needs to be outside
1302 $title = array_shift( $target );
1303 if( $forceKnown ) {
1304 $link = $sk->link(
1305 $title,
1306 htmlspecialchars( $title->getFullText() ),
1307 array(),
1308 array(),
1309 array( 'known', 'noclasses' )
1310 );
1311 } else {
1312 $link = $sk->link( $title, htmlspecialchars( $title->getFullText() ) );
1313 }
1314 // automatically append redirect=no to each link, since most of them are redirect pages themselves
1315 foreach( $target as $rt ) {
1316 if( $forceKnown ) {
1317 $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
1318 . $sk->link(
1319 $rt,
1320 htmlspecialchars( $rt->getFullText() ),
1321 array(),
1322 array(),
1323 array( 'known', 'noclasses' )
1324 );
1325 } else {
1326 $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
1327 . $sk->link( $rt, htmlspecialchars( $rt->getFullText() ) );
1328 }
1329 }
1330 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
1331 '<span class="redirectText">'.$link.'</span>';
1332
1333 }
1334
1335 public function addTrackbacks() {
1336 global $wgOut, $wgUser;
1337 $dbr = wfGetDB( DB_SLAVE );
1338 $tbs = $dbr->select( 'trackbacks',
1339 array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
1340 array('tb_page' => $this->getID() )
1341 );
1342 if( !$dbr->numRows($tbs) ) return;
1343
1344 $tbtext = "";
1345 while( $o = $dbr->fetchObject($tbs) ) {
1346 $rmvtxt = "";
1347 if( $wgUser->isAllowed( 'trackback' ) ) {
1348 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid=" .
1349 $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
1350 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1351 }
1352 $tbtext .= "\n";
1353 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
1354 $o->tb_title,
1355 $o->tb_url,
1356 $o->tb_ex,
1357 $o->tb_name,
1358 $rmvtxt);
1359 }
1360 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>$1</div>\n", array( 'trackbackbox', $tbtext ) );
1361 $this->mTitle->invalidateCache();
1362 }
1363
1364 public function deletetrackback() {
1365 global $wgUser, $wgRequest, $wgOut;
1366 if( !$wgUser->matchEditToken($wgRequest->getVal('token')) ) {
1367 $wgOut->addWikiMsg( 'sessionfailure' );
1368 return;
1369 }
1370
1371 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
1372 if( count($permission_errors) ) {
1373 $wgOut->showPermissionsErrorPage( $permission_errors );
1374 return;
1375 }
1376
1377 $db = wfGetDB( DB_MASTER );
1378 $db->delete( 'trackbacks', array('tb_id' => $wgRequest->getInt('tbid')) );
1379
1380 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1381 $this->mTitle->invalidateCache();
1382 }
1383
1384 public function render() {
1385 global $wgOut;
1386 $wgOut->setArticleBodyOnly(true);
1387 $this->view();
1388 }
1389
1390 /**
1391 * Handle action=purge
1392 */
1393 public function purge() {
1394 global $wgUser, $wgRequest, $wgOut;
1395 if( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
1396 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1397 $this->doPurge();
1398 $this->view();
1399 }
1400 } else {
1401 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1402 $button = wfMsgExt( 'confirm_purge_button', array('escapenoentities') );
1403 $form = "<form method=\"post\" action=\"$action\">\n" .
1404 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1405 "</form>\n";
1406 $top = wfMsgExt( 'confirm-purge-top', array('parse') );
1407 $bottom = wfMsgExt( 'confirm-purge-bottom', array('parse') );
1408 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1409 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1410 $wgOut->addHTML( $top . $form . $bottom );
1411 }
1412 }
1413
1414 /**
1415 * Perform the actions of a page purging
1416 */
1417 public function doPurge() {
1418 global $wgUseSquid;
1419 // Invalidate the cache
1420 $this->mTitle->invalidateCache();
1421
1422 if( $wgUseSquid ) {
1423 // Commit the transaction before the purge is sent
1424 $dbw = wfGetDB( DB_MASTER );
1425 $dbw->immediateCommit();
1426
1427 // Send purge
1428 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1429 $update->doUpdate();
1430 }
1431 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1432 global $wgMessageCache;
1433 if( $this->getID() == 0 ) {
1434 $text = false;
1435 } else {
1436 $text = $this->getRawText();
1437 }
1438 $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
1439 }
1440 }
1441
1442 /**
1443 * Insert a new empty page record for this article.
1444 * This *must* be followed up by creating a revision
1445 * and running $this->updateToLatest( $rev_id );
1446 * or else the record will be left in a funky state.
1447 * Best if all done inside a transaction.
1448 *
1449 * @param $dbw Database
1450 * @return int The newly created page_id key, or false if the title already existed
1451 * @private
1452 */
1453 public function insertOn( $dbw ) {
1454 wfProfileIn( __METHOD__ );
1455
1456 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1457 $dbw->insert( 'page', array(
1458 'page_id' => $page_id,
1459 'page_namespace' => $this->mTitle->getNamespace(),
1460 'page_title' => $this->mTitle->getDBkey(),
1461 'page_counter' => 0,
1462 'page_restrictions' => '',
1463 'page_is_redirect' => 0, # Will set this shortly...
1464 'page_is_new' => 1,
1465 'page_random' => wfRandom(),
1466 'page_touched' => $dbw->timestamp(),
1467 'page_latest' => 0, # Fill this in shortly...
1468 'page_len' => 0, # Fill this in shortly...
1469 ), __METHOD__, 'IGNORE' );
1470
1471 $affected = $dbw->affectedRows();
1472 if( $affected ) {
1473 $newid = $dbw->insertId();
1474 $this->mTitle->resetArticleId( $newid );
1475 }
1476 wfProfileOut( __METHOD__ );
1477 return $affected ? $newid : false;
1478 }
1479
1480 /**
1481 * Update the page record to point to a newly saved revision.
1482 *
1483 * @param $dbw Database object
1484 * @param $revision Revision: For ID number, and text used to set
1485 length and redirect status fields
1486 * @param $lastRevision Integer: if given, will not overwrite the page field
1487 * when different from the currently set value.
1488 * Giving 0 indicates the new page flag should be set
1489 * on.
1490 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1491 * removing rows in redirect table.
1492 * @return bool true on success, false on failure
1493 * @private
1494 */
1495 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1496 wfProfileIn( __METHOD__ );
1497
1498 $text = $revision->getText();
1499 $rt = Title::newFromRedirect( $text );
1500
1501 $conditions = array( 'page_id' => $this->getId() );
1502 if( !is_null( $lastRevision ) ) {
1503 # An extra check against threads stepping on each other
1504 $conditions['page_latest'] = $lastRevision;
1505 }
1506
1507 $dbw->update( 'page',
1508 array( /* SET */
1509 'page_latest' => $revision->getId(),
1510 'page_touched' => $dbw->timestamp(),
1511 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1512 'page_is_redirect' => $rt !== NULL ? 1 : 0,
1513 'page_len' => strlen( $text ),
1514 ),
1515 $conditions,
1516 __METHOD__ );
1517
1518 $result = $dbw->affectedRows() != 0;
1519 if( $result ) {
1520 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1521 }
1522
1523 wfProfileOut( __METHOD__ );
1524 return $result;
1525 }
1526
1527 /**
1528 * Add row to the redirect table if this is a redirect, remove otherwise.
1529 *
1530 * @param $dbw Database
1531 * @param $redirectTitle a title object pointing to the redirect target,
1532 * or NULL if this is not a redirect
1533 * @param $lastRevIsRedirect If given, will optimize adding and
1534 * removing rows in redirect table.
1535 * @return bool true on success, false on failure
1536 * @private
1537 */
1538 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1539 // Always update redirects (target link might have changed)
1540 // Update/Insert if we don't know if the last revision was a redirect or not
1541 // Delete if changing from redirect to non-redirect
1542 $isRedirect = !is_null($redirectTitle);
1543 if($isRedirect || is_null($lastRevIsRedirect) || $lastRevIsRedirect !== $isRedirect) {
1544 wfProfileIn( __METHOD__ );
1545 if( $isRedirect ) {
1546 // This title is a redirect, Add/Update row in the redirect table
1547 $set = array( /* SET */
1548 'rd_namespace' => $redirectTitle->getNamespace(),
1549 'rd_title' => $redirectTitle->getDBkey(),
1550 'rd_from' => $this->getId(),
1551 );
1552 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
1553 } else {
1554 // This is not a redirect, remove row from redirect table
1555 $where = array( 'rd_from' => $this->getId() );
1556 $dbw->delete( 'redirect', $where, __METHOD__);
1557 }
1558 if( $this->getTitle()->getNamespace() == NS_FILE ) {
1559 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1560 }
1561 wfProfileOut( __METHOD__ );
1562 return ( $dbw->affectedRows() != 0 );
1563 }
1564 return true;
1565 }
1566
1567 /**
1568 * If the given revision is newer than the currently set page_latest,
1569 * update the page record. Otherwise, do nothing.
1570 *
1571 * @param $dbw Database object
1572 * @param $revision Revision object
1573 */
1574 public function updateIfNewerOn( &$dbw, $revision ) {
1575 wfProfileIn( __METHOD__ );
1576 $row = $dbw->selectRow(
1577 array( 'revision', 'page' ),
1578 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1579 array(
1580 'page_id' => $this->getId(),
1581 'page_latest=rev_id' ),
1582 __METHOD__ );
1583 if( $row ) {
1584 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1585 wfProfileOut( __METHOD__ );
1586 return false;
1587 }
1588 $prev = $row->rev_id;
1589 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1590 } else {
1591 # No or missing previous revision; mark the page as new
1592 $prev = 0;
1593 $lastRevIsRedirect = null;
1594 }
1595 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1596 wfProfileOut( __METHOD__ );
1597 return $ret;
1598 }
1599
1600 /**
1601 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1602 * @return string Complete article text, or null if error
1603 */
1604 public function replaceSection( $section, $text, $summary = '', $edittime = NULL ) {
1605 wfProfileIn( __METHOD__ );
1606 if( strval( $section ) == '' ) {
1607 // Whole-page edit; let the whole text through
1608 } else {
1609 if( is_null($edittime) ) {
1610 $rev = Revision::newFromTitle( $this->mTitle );
1611 } else {
1612 $dbw = wfGetDB( DB_MASTER );
1613 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1614 }
1615 if( !$rev ) {
1616 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1617 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1618 return null;
1619 }
1620 $oldtext = $rev->getText();
1621
1622 if( $section == 'new' ) {
1623 # Inserting a new section
1624 $subject = $summary ? wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1625 $text = strlen( trim( $oldtext ) ) > 0
1626 ? "{$oldtext}\n\n{$subject}{$text}"
1627 : "{$subject}{$text}";
1628 } else {
1629 # Replacing an existing section; roll out the big guns
1630 global $wgParser;
1631 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1632 }
1633 }
1634 wfProfileOut( __METHOD__ );
1635 return $text;
1636 }
1637
1638 /**
1639 * This function is not deprecated until somebody fixes the core not to use
1640 * it. Nevertheless, use Article::doEdit() instead.
1641 */
1642 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1643 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1644 ( $isminor ? EDIT_MINOR : 0 ) |
1645 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
1646 ( $bot ? EDIT_FORCE_BOT : 0 );
1647
1648 # If this is a comment, add the summary as headline
1649 if( $comment && $summary != "" ) {
1650 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1651 }
1652
1653 $this->doEdit( $text, $summary, $flags );
1654
1655 $dbw = wfGetDB( DB_MASTER );
1656 if($watchthis) {
1657 if(!$this->mTitle->userIsWatching()) {
1658 $dbw->begin();
1659 $this->doWatch();
1660 $dbw->commit();
1661 }
1662 } else {
1663 if( $this->mTitle->userIsWatching() ) {
1664 $dbw->begin();
1665 $this->doUnwatch();
1666 $dbw->commit();
1667 }
1668 }
1669 $this->doRedirect( $this->isRedirect( $text ) );
1670 }
1671
1672 /**
1673 * @deprecated use Article::doEdit()
1674 */
1675 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1676 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1677 ( $minor ? EDIT_MINOR : 0 ) |
1678 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1679
1680 $status = $this->doEdit( $text, $summary, $flags );
1681 if( !$status->isOK() ) {
1682 return false;
1683 }
1684
1685 $dbw = wfGetDB( DB_MASTER );
1686 if( $watchthis ) {
1687 if(!$this->mTitle->userIsWatching()) {
1688 $dbw->begin();
1689 $this->doWatch();
1690 $dbw->commit();
1691 }
1692 } else {
1693 if( $this->mTitle->userIsWatching() ) {
1694 $dbw->begin();
1695 $this->doUnwatch();
1696 $dbw->commit();
1697 }
1698 }
1699
1700 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1701 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1702
1703 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1704 return true;
1705 }
1706
1707 /**
1708 * Article::doEdit()
1709 *
1710 * Change an existing article or create a new article. Updates RC and all necessary caches,
1711 * optionally via the deferred update array.
1712 *
1713 * $wgUser must be set before calling this function.
1714 *
1715 * @param $text String: new text
1716 * @param $summary String: edit summary
1717 * @param $flags Integer bitfield:
1718 * EDIT_NEW
1719 * Article is known or assumed to be non-existent, create a new one
1720 * EDIT_UPDATE
1721 * Article is known or assumed to be pre-existing, update it
1722 * EDIT_MINOR
1723 * Mark this edit minor, if the user is allowed to do so
1724 * EDIT_SUPPRESS_RC
1725 * Do not log the change in recentchanges
1726 * EDIT_FORCE_BOT
1727 * Mark the edit a "bot" edit regardless of user rights
1728 * EDIT_DEFER_UPDATES
1729 * Defer some of the updates until the end of index.php
1730 * EDIT_AUTOSUMMARY
1731 * Fill in blank summaries with generated text where possible
1732 *
1733 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1734 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1735 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1736 * edit-already-exists error will be returned. These two conditions are also possible with
1737 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1738 *
1739 * @param $baseRevId the revision ID this edit was based off, if any
1740 * @param $user Optional user object, $wgUser will be used if not passed
1741 *
1742 * @return Status object. Possible errors:
1743 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1744 * edit-gone-missing: In update mode, but the article didn't exist
1745 * edit-conflict: In update mode, the article changed unexpectedly
1746 * edit-no-change: Warning that the text was the same as before
1747 * edit-already-exists: In creation mode, but the article already exists
1748 *
1749 * Extensions may define additional errors.
1750 *
1751 * $return->value will contain an associative array with members as follows:
1752 * new: Boolean indicating if the function attempted to create a new article
1753 * revision: The revision object for the inserted revision, or null
1754 *
1755 * Compatibility note: this function previously returned a boolean value indicating success/failure
1756 */
1757 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1758 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1759
1760 # Low-level sanity check
1761 if( $this->mTitle->getText() == '' ) {
1762 throw new MWException( 'Something is trying to edit an article with an empty title' );
1763 }
1764
1765 wfProfileIn( __METHOD__ );
1766
1767 $user = is_null($user) ? $wgUser : $user;
1768 $status = Status::newGood( array() );
1769
1770 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1771 $this->loadPageData();
1772
1773 if( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
1774 $aid = $this->mTitle->getArticleID();
1775 if( $aid ) {
1776 $flags |= EDIT_UPDATE;
1777 } else {
1778 $flags |= EDIT_NEW;
1779 }
1780 }
1781
1782 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1783 $flags & EDIT_MINOR, null, null, &$flags, &$status ) ) )
1784 {
1785 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1786 wfProfileOut( __METHOD__ );
1787 if( $status->isOK() ) {
1788 $status->fatal( 'edit-hook-aborted');
1789 }
1790 return $status;
1791 }
1792
1793 # Silently ignore EDIT_MINOR if not allowed
1794 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed('minoredit');
1795 $bot = $flags & EDIT_FORCE_BOT;
1796
1797 $oldtext = $this->getRawText(); // current revision
1798 $oldsize = strlen( $oldtext );
1799
1800 # Provide autosummaries if one is not provided and autosummaries are enabled.
1801 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1802 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1803 }
1804
1805 $editInfo = $this->prepareTextForEdit( $text );
1806 $text = $editInfo->pst;
1807 $newsize = strlen( $text );
1808
1809 $dbw = wfGetDB( DB_MASTER );
1810 $now = wfTimestampNow();
1811
1812 if( $flags & EDIT_UPDATE ) {
1813 # Update article, but only if changed.
1814 $status->value['new'] = false;
1815 # Make sure the revision is either completely inserted or not inserted at all
1816 if( !$wgDBtransactions ) {
1817 $userAbort = ignore_user_abort( true );
1818 }
1819
1820 $revisionId = 0;
1821
1822 $changed = ( strcmp( $text, $oldtext ) != 0 );
1823
1824 if( $changed ) {
1825 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1826 - (int)$this->isCountable( $oldtext );
1827 $this->mTotalAdjustment = 0;
1828
1829 if( !$this->mLatest ) {
1830 # Article gone missing
1831 wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" );
1832 $status->fatal( 'edit-gone-missing' );
1833 wfProfileOut( __METHOD__ );
1834 return $status;
1835 }
1836
1837 $revision = new Revision( array(
1838 'page' => $this->getId(),
1839 'comment' => $summary,
1840 'minor_edit' => $isminor,
1841 'text' => $text,
1842 'parent_id' => $this->mLatest,
1843 'user' => $user->getId(),
1844 'user_text' => $user->getName(),
1845 ) );
1846
1847 $dbw->begin();
1848 $revisionId = $revision->insertOn( $dbw );
1849
1850 # Update page
1851 #
1852 # Note that we use $this->mLatest instead of fetching a value from the master DB
1853 # during the course of this function. This makes sure that EditPage can detect
1854 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1855 # before this function is called. A previous function used a separate query, this
1856 # creates a window where concurrent edits can cause an ignored edit conflict.
1857 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest );
1858
1859 if( !$ok ) {
1860 /* Belated edit conflict! Run away!! */
1861 $status->fatal( 'edit-conflict' );
1862 # Delete the invalid revision if the DB is not transactional
1863 if( !$wgDBtransactions ) {
1864 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
1865 }
1866 $revisionId = 0;
1867 $dbw->rollback();
1868 } else {
1869 global $wgUseRCPatrol;
1870 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, $baseRevId, $user) );
1871 # Update recentchanges
1872 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1873 # Mark as patrolled if the user can do so
1874 $patrolled = $wgUseRCPatrol && $this->mTitle->userCan('autopatrol');
1875 # Add RC row to the DB
1876 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1877 $this->mLatest, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1878 $revisionId, $patrolled
1879 );
1880 # Log auto-patrolled edits
1881 if( $patrolled ) {
1882 PatrolLog::record( $rc, true );
1883 }
1884 }
1885 $user->incEditCount();
1886 $dbw->commit();
1887 }
1888 } else {
1889 $status->warning( 'edit-no-change' );
1890 $revision = null;
1891 // Keep the same revision ID, but do some updates on it
1892 $revisionId = $this->getRevIdFetched();
1893 // Update page_touched, this is usually implicit in the page update
1894 // Other cache updates are done in onArticleEdit()
1895 $this->mTitle->invalidateCache();
1896 }
1897
1898 if( !$wgDBtransactions ) {
1899 ignore_user_abort( $userAbort );
1900 }
1901 // Now that ignore_user_abort is restored, we can respond to fatal errors
1902 if( !$status->isOK() ) {
1903 wfProfileOut( __METHOD__ );
1904 return $status;
1905 }
1906
1907 # Invalidate cache of this article and all pages using this article
1908 # as a template. Partly deferred.
1909 Article::onArticleEdit( $this->mTitle );
1910 # Update links tables, site stats, etc.
1911 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1912 } else {
1913 # Create new article
1914 $status->value['new'] = true;
1915
1916 # Set statistics members
1917 # We work out if it's countable after PST to avoid counter drift
1918 # when articles are created with {{subst:}}
1919 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1920 $this->mTotalAdjustment = 1;
1921
1922 $dbw->begin();
1923
1924 # Add the page record; stake our claim on this title!
1925 # This will return false if the article already exists
1926 $newid = $this->insertOn( $dbw );
1927
1928 if( $newid === false ) {
1929 $dbw->rollback();
1930 $status->fatal( 'edit-already-exists' );
1931 wfProfileOut( __METHOD__ );
1932 return $status;
1933 }
1934
1935 # Save the revision text...
1936 $revision = new Revision( array(
1937 'page' => $newid,
1938 'comment' => $summary,
1939 'minor_edit' => $isminor,
1940 'text' => $text,
1941 'user' => $user->getId(),
1942 'user_text' => $user->getName(),
1943 ) );
1944 $revisionId = $revision->insertOn( $dbw );
1945
1946 $this->mTitle->resetArticleID( $newid );
1947
1948 # Update the page record with revision data
1949 $this->updateRevisionOn( $dbw, $revision, 0 );
1950
1951 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $user) );
1952 # Update recentchanges
1953 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1954 global $wgUseRCPatrol, $wgUseNPPatrol;
1955 # Mark as patrolled if the user can do so
1956 $patrolled = ($wgUseRCPatrol || $wgUseNPPatrol) && $this->mTitle->userCan('autopatrol');
1957 # Add RC row to the DB
1958 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1959 '', strlen($text), $revisionId, $patrolled );
1960 # Log auto-patrolled edits
1961 if( $patrolled ) {
1962 PatrolLog::record( $rc, true );
1963 }
1964 }
1965 $user->incEditCount();
1966 $dbw->commit();
1967
1968 # Update links, etc.
1969 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1970
1971 # Clear caches
1972 Article::onArticleCreate( $this->mTitle );
1973
1974 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1975 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1976 }
1977
1978 # Do updates right now unless deferral was requested
1979 if( !( $flags & EDIT_DEFER_UPDATES ) ) {
1980 wfDoUpdates();
1981 }
1982
1983 // Return the new revision (or null) to the caller
1984 $status->value['revision'] = $revision;
1985
1986 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1987 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
1988
1989 wfProfileOut( __METHOD__ );
1990 return $status;
1991 }
1992
1993 /**
1994 * @deprecated wrapper for doRedirect
1995 */
1996 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1997 wfDeprecated( __METHOD__ );
1998 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1999 }
2000
2001 /**
2002 * Output a redirect back to the article.
2003 * This is typically used after an edit.
2004 *
2005 * @param $noRedir Boolean: add redirect=no
2006 * @param $sectionAnchor String: section to redirect to, including "#"
2007 * @param $extraQuery String: extra query params
2008 */
2009 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2010 global $wgOut;
2011 if( $noRedir ) {
2012 $query = 'redirect=no';
2013 if( $extraQuery )
2014 $query .= "&$query";
2015 } else {
2016 $query = $extraQuery;
2017 }
2018 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
2019 }
2020
2021 /**
2022 * Mark this particular edit/page as patrolled
2023 */
2024 public function markpatrolled() {
2025 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
2026 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2027
2028 # If we haven't been given an rc_id value, we can't do anything
2029 $rcid = (int) $wgRequest->getVal('rcid');
2030 $rc = RecentChange::newFromId($rcid);
2031 if( is_null($rc) ) {
2032 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2033 return;
2034 }
2035
2036 #It would be nice to see where the user had actually come from, but for now just guess
2037 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
2038 $return = SpecialPage::getTitleFor( $returnto );
2039
2040 $dbw = wfGetDB( DB_MASTER );
2041 $errors = $rc->doMarkPatrolled();
2042
2043 if( in_array(array('rcpatroldisabled'), $errors) ) {
2044 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2045 return;
2046 }
2047
2048 if( in_array(array('hookaborted'), $errors) ) {
2049 // The hook itself has handled any output
2050 return;
2051 }
2052
2053 if( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
2054 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2055 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2056 $wgOut->returnToMain( false, $return );
2057 return;
2058 }
2059
2060 if( !empty($errors) ) {
2061 $wgOut->showPermissionsErrorPage( $errors );
2062 return;
2063 }
2064
2065 # Inform the user
2066 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2067 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
2068 $wgOut->returnToMain( false, $return );
2069 }
2070
2071 /**
2072 * User-interface handler for the "watch" action
2073 */
2074
2075 public function watch() {
2076 global $wgUser, $wgOut;
2077 if( $wgUser->isAnon() ) {
2078 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2079 return;
2080 }
2081 if( wfReadOnly() ) {
2082 $wgOut->readOnlyPage();
2083 return;
2084 }
2085 if( $this->doWatch() ) {
2086 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
2087 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2088 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
2089 }
2090 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2091 }
2092
2093 /**
2094 * Add this page to $wgUser's watchlist
2095 * @return bool true on successful watch operation
2096 */
2097 public function doWatch() {
2098 global $wgUser;
2099 if( $wgUser->isAnon() ) {
2100 return false;
2101 }
2102 if( wfRunHooks('WatchArticle', array(&$wgUser, &$this)) ) {
2103 $wgUser->addWatch( $this->mTitle );
2104 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
2105 }
2106 return false;
2107 }
2108
2109 /**
2110 * User interface handler for the "unwatch" action.
2111 */
2112 public function unwatch() {
2113 global $wgUser, $wgOut;
2114 if( $wgUser->isAnon() ) {
2115 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2116 return;
2117 }
2118 if( wfReadOnly() ) {
2119 $wgOut->readOnlyPage();
2120 return;
2121 }
2122 if( $this->doUnwatch() ) {
2123 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
2124 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2125 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
2126 }
2127 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2128 }
2129
2130 /**
2131 * Stop watching a page
2132 * @return bool true on successful unwatch
2133 */
2134 public function doUnwatch() {
2135 global $wgUser;
2136 if( $wgUser->isAnon() ) {
2137 return false;
2138 }
2139 if( wfRunHooks('UnwatchArticle', array(&$wgUser, &$this)) ) {
2140 $wgUser->removeWatch( $this->mTitle );
2141 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
2142 }
2143 return false;
2144 }
2145
2146 /**
2147 * action=protect handler
2148 */
2149 public function protect() {
2150 $form = new ProtectionForm( $this );
2151 $form->execute();
2152 }
2153
2154 /**
2155 * action=unprotect handler (alias)
2156 */
2157 public function unprotect() {
2158 $this->protect();
2159 }
2160
2161 /**
2162 * Update the article's restriction field, and leave a log entry.
2163 *
2164 * @param $limit Array: set of restriction keys
2165 * @param $reason String
2166 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2167 * @param $expiry Array: per restriction type expiration
2168 * @return bool true on success
2169 */
2170 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2171 global $wgUser, $wgRestrictionTypes, $wgContLang;
2172
2173 $id = $this->mTitle->getArticleID();
2174 if ( $id <= 0 ) {
2175 wfDebug( "updateRestrictions failed: $id <= 0\n" );
2176 return false;
2177 }
2178
2179 if ( wfReadOnly() ) {
2180 wfDebug( "updateRestrictions failed: read-only\n" );
2181 return false;
2182 }
2183
2184 if ( !$this->mTitle->userCan( 'protect' ) ) {
2185 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2186 return false;
2187 }
2188
2189 if( !$cascade ) {
2190 $cascade = false;
2191 }
2192
2193 // Take this opportunity to purge out expired restrictions
2194 Title::purgeExpiredRestrictions();
2195
2196 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2197 # we expect a single selection, but the schema allows otherwise.
2198 $current = array();
2199 $updated = Article::flattenRestrictions( $limit );
2200 $changed = false;
2201 foreach( $wgRestrictionTypes as $action ) {
2202 if( isset( $expiry[$action] ) ) {
2203 # Get current restrictions on $action
2204 $aLimits = $this->mTitle->getRestrictions( $action );
2205 $current[$action] = implode( '', $aLimits );
2206 # Are any actual restrictions being dealt with here?
2207 $aRChanged = count($aLimits) || !empty($limit[$action]);
2208 # If something changed, we need to log it. Checking $aRChanged
2209 # assures that "unprotecting" a page that is not protected does
2210 # not log just because the expiry was "changed".
2211 if( $aRChanged && $this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action] ) {
2212 $changed = true;
2213 }
2214 }
2215 }
2216
2217 $current = Article::flattenRestrictions( $current );
2218
2219 $changed = ($changed || $current != $updated );
2220 $changed = $changed || ($updated && $this->mTitle->areRestrictionsCascading() != $cascade);
2221 $protect = ( $updated != '' );
2222
2223 # If nothing's changed, do nothing
2224 if( $changed ) {
2225 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2226
2227 $dbw = wfGetDB( DB_MASTER );
2228
2229 # Prepare a null revision to be added to the history
2230 $modified = $current != '' && $protect;
2231 if( $protect ) {
2232 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
2233 } else {
2234 $comment_type = 'unprotectedarticle';
2235 }
2236 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
2237
2238 # Only restrictions with the 'protect' right can cascade...
2239 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2240 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
2241 # The schema allows multiple restrictions
2242 if(!in_array('protect', $editrestriction) && !in_array('sysop', $editrestriction))
2243 $cascade = false;
2244 $cascade_description = '';
2245 if( $cascade ) {
2246 $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';
2247 }
2248
2249 if( $reason )
2250 $comment .= ": $reason";
2251
2252 $editComment = $comment;
2253 $encodedExpiry = array();
2254 $protect_description = '';
2255 foreach( $limit as $action => $restrictions ) {
2256 if ( !isset($expiry[$action]) )
2257 $expiry[$action] = 'infinite';
2258
2259 $encodedExpiry[$action] = Block::encodeExpiry($expiry[$action], $dbw );
2260 if( $restrictions != '' ) {
2261 $protect_description .= "[$action=$restrictions] (";
2262 if( $encodedExpiry[$action] != 'infinity' ) {
2263 $protect_description .= wfMsgForContent( 'protect-expiring',
2264 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2265 $wgContLang->date( $expiry[$action], false, false ) ,
2266 $wgContLang->time( $expiry[$action], false, false ) );
2267 } else {
2268 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2269 }
2270 $protect_description .= ') ';
2271 }
2272 }
2273 $protect_description = trim($protect_description);
2274
2275 if( $protect_description && $protect )
2276 $editComment .= " ($protect_description)";
2277 if( $cascade )
2278 $editComment .= "$cascade_description";
2279 # Update restrictions table
2280 foreach( $limit as $action => $restrictions ) {
2281 if($restrictions != '' ) {
2282 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
2283 array( 'pr_page' => $id,
2284 'pr_type' => $action,
2285 'pr_level' => $restrictions,
2286 'pr_cascade' => ($cascade && $action == 'edit') ? 1 : 0,
2287 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__ );
2288 } else {
2289 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2290 'pr_type' => $action ), __METHOD__ );
2291 }
2292 }
2293
2294 # Insert a null revision
2295 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
2296 $nullRevId = $nullRevision->insertOn( $dbw );
2297
2298 $latest = $this->getLatest();
2299 # Update page record
2300 $dbw->update( 'page',
2301 array( /* SET */
2302 'page_touched' => $dbw->timestamp(),
2303 'page_restrictions' => '',
2304 'page_latest' => $nullRevId
2305 ), array( /* WHERE */
2306 'page_id' => $id
2307 ), 'Article::protect'
2308 );
2309
2310 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest, $wgUser) );
2311 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2312
2313 # Update the protection log
2314 $log = new LogPage( 'protect' );
2315 if( $protect ) {
2316 $params = array($protect_description,$cascade ? 'cascade' : '');
2317 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason), $params );
2318 } else {
2319 $log->addEntry( 'unprotect', $this->mTitle, $reason );
2320 }
2321
2322 } # End hook
2323 } # End "changed" check
2324
2325 return true;
2326 }
2327
2328 /**
2329 * Take an array of page restrictions and flatten it to a string
2330 * suitable for insertion into the page_restrictions field.
2331 * @param $limit Array
2332 * @return String
2333 */
2334 protected static function flattenRestrictions( $limit ) {
2335 if( !is_array( $limit ) ) {
2336 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2337 }
2338 $bits = array();
2339 ksort( $limit );
2340 foreach( $limit as $action => $restrictions ) {
2341 if( $restrictions != '' ) {
2342 $bits[] = "$action=$restrictions";
2343 }
2344 }
2345 return implode( ':', $bits );
2346 }
2347
2348 /**
2349 * Auto-generates a deletion reason
2350 * @param &$hasHistory Boolean: whether the page has a history
2351 */
2352 public function generateReason( &$hasHistory ) {
2353 global $wgContLang;
2354 $dbw = wfGetDB( DB_MASTER );
2355 // Get the last revision
2356 $rev = Revision::newFromTitle( $this->mTitle );
2357 if( is_null( $rev ) )
2358 return false;
2359
2360 // Get the article's contents
2361 $contents = $rev->getText();
2362 $blank = false;
2363 // If the page is blank, use the text from the previous revision,
2364 // which can only be blank if there's a move/import/protect dummy revision involved
2365 if( $contents == '' ) {
2366 $prev = $rev->getPrevious();
2367 if( $prev ) {
2368 $contents = $prev->getText();
2369 $blank = true;
2370 }
2371 }
2372
2373 // Find out if there was only one contributor
2374 // Only scan the last 20 revisions
2375 $res = $dbw->select( 'revision', 'rev_user_text',
2376 array( 'rev_page' => $this->getID(), $dbw->bitAnd('rev_deleted', Revision::DELETED_USER) . ' = 0' ),
2377 __METHOD__,
2378 array( 'LIMIT' => 20 )
2379 );
2380 if( $res === false )
2381 // This page has no revisions, which is very weird
2382 return false;
2383
2384 $hasHistory = ( $res->numRows() > 1 );
2385 $row = $dbw->fetchObject( $res );
2386 $onlyAuthor = $row->rev_user_text;
2387 // Try to find a second contributor
2388 foreach( $res as $row ) {
2389 if( $row->rev_user_text != $onlyAuthor ) {
2390 $onlyAuthor = false;
2391 break;
2392 }
2393 }
2394 $dbw->freeResult( $res );
2395
2396 // Generate the summary with a '$1' placeholder
2397 if( $blank ) {
2398 // The current revision is blank and the one before is also
2399 // blank. It's just not our lucky day
2400 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2401 } else {
2402 if( $onlyAuthor )
2403 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2404 else
2405 $reason = wfMsgForContent( 'excontent', '$1' );
2406 }
2407
2408 if( $reason == '-' ) {
2409 // Allow these UI messages to be blanked out cleanly
2410 return '';
2411 }
2412
2413 // Replace newlines with spaces to prevent uglyness
2414 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2415 // Calculate the maximum amount of chars to get
2416 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2417 $maxLength = 255 - (strlen( $reason ) - 2) - 3;
2418 $contents = $wgContLang->truncate( $contents, $maxLength );
2419 // Remove possible unfinished links
2420 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2421 // Now replace the '$1' placeholder
2422 $reason = str_replace( '$1', $contents, $reason );
2423 return $reason;
2424 }
2425
2426
2427 /*
2428 * UI entry point for page deletion
2429 */
2430 public function delete() {
2431 global $wgUser, $wgOut, $wgRequest;
2432
2433 $confirm = $wgRequest->wasPosted() &&
2434 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2435
2436 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2437 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2438
2439 $reason = $this->DeleteReasonList;
2440
2441 if( $reason != 'other' && $this->DeleteReason != '' ) {
2442 // Entry from drop down menu + additional comment
2443 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason;
2444 } elseif( $reason == 'other' ) {
2445 $reason = $this->DeleteReason;
2446 }
2447 # Flag to hide all contents of the archived revisions
2448 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2449
2450 # This code desperately needs to be totally rewritten
2451
2452 # Read-only check...
2453 if( wfReadOnly() ) {
2454 $wgOut->readOnlyPage();
2455 return;
2456 }
2457
2458 # Check permissions
2459 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
2460
2461 if( count( $permission_errors ) > 0 ) {
2462 $wgOut->showPermissionsErrorPage( $permission_errors );
2463 return;
2464 }
2465
2466 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2467
2468 # Better double-check that it hasn't been deleted yet!
2469 $dbw = wfGetDB( DB_MASTER );
2470 $conds = $this->mTitle->pageCond();
2471 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2472 if( $latest === false ) {
2473 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2474 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2475 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2476 return;
2477 }
2478
2479 # Hack for big sites
2480 $bigHistory = $this->isBigDeletion();
2481 if( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2482 global $wgLang, $wgDeleteRevisionsLimit;
2483 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2484 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2485 return;
2486 }
2487
2488 if( $confirm ) {
2489 $this->doDelete( $reason, $suppress );
2490 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2491 $this->doWatch();
2492 } elseif( $this->mTitle->userIsWatching() ) {
2493 $this->doUnwatch();
2494 }
2495 return;
2496 }
2497
2498 // Generate deletion reason
2499 $hasHistory = false;
2500 if( !$reason ) $reason = $this->generateReason($hasHistory);
2501
2502 // If the page has a history, insert a warning
2503 if( $hasHistory && !$confirm ) {
2504 $skin = $wgUser->getSkin();
2505 $wgOut->addHTML( '<strong>' . wfMsgExt( 'historywarning', array( 'parseinline' ) ) . ' ' . $skin->historyLink() . '</strong>' );
2506 if( $bigHistory ) {
2507 global $wgLang, $wgDeleteRevisionsLimit;
2508 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2509 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2510 }
2511 }
2512
2513 return $this->confirmDelete( $reason );
2514 }
2515
2516 /**
2517 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2518 */
2519 public function isBigDeletion() {
2520 global $wgDeleteRevisionsLimit;
2521 if( $wgDeleteRevisionsLimit ) {
2522 $revCount = $this->estimateRevisionCount();
2523 return $revCount > $wgDeleteRevisionsLimit;
2524 }
2525 return false;
2526 }
2527
2528 /**
2529 * @return int approximate revision count
2530 */
2531 public function estimateRevisionCount() {
2532 $dbr = wfGetDB( DB_SLAVE );
2533 // For an exact count...
2534 //return $dbr->selectField( 'revision', 'COUNT(*)',
2535 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2536 return $dbr->estimateRowCount( 'revision', '*',
2537 array( 'rev_page' => $this->getId() ), __METHOD__ );
2538 }
2539
2540 /**
2541 * Get the last N authors
2542 * @param $num Integer: number of revisions to get
2543 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2544 * @return array Array of authors, duplicates not removed
2545 */
2546 public function getLastNAuthors( $num, $revLatest = 0 ) {
2547 wfProfileIn( __METHOD__ );
2548 // First try the slave
2549 // If that doesn't have the latest revision, try the master
2550 $continue = 2;
2551 $db = wfGetDB( DB_SLAVE );
2552 do {
2553 $res = $db->select( array( 'page', 'revision' ),
2554 array( 'rev_id', 'rev_user_text' ),
2555 array(
2556 'page_namespace' => $this->mTitle->getNamespace(),
2557 'page_title' => $this->mTitle->getDBkey(),
2558 'rev_page = page_id'
2559 ), __METHOD__, $this->getSelectOptions( array(
2560 'ORDER BY' => 'rev_timestamp DESC',
2561 'LIMIT' => $num
2562 ) )
2563 );
2564 if( !$res ) {
2565 wfProfileOut( __METHOD__ );
2566 return array();
2567 }
2568 $row = $db->fetchObject( $res );
2569 if( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2570 $db = wfGetDB( DB_MASTER );
2571 $continue--;
2572 } else {
2573 $continue = 0;
2574 }
2575 } while ( $continue );
2576
2577 $authors = array( $row->rev_user_text );
2578 while ( $row = $db->fetchObject( $res ) ) {
2579 $authors[] = $row->rev_user_text;
2580 }
2581 wfProfileOut( __METHOD__ );
2582 return $authors;
2583 }
2584
2585 /**
2586 * Output deletion confirmation dialog
2587 * @param $reason String: prefilled reason
2588 */
2589 public function confirmDelete( $reason ) {
2590 global $wgOut, $wgUser;
2591
2592 wfDebug( "Article::confirmDelete\n" );
2593
2594 $deleteBackLink = $wgUser->getSkin()->link(
2595 $this->mTitle,
2596 null,
2597 array(),
2598 array(),
2599 array( 'known', 'noclasses' )
2600 );
2601 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2602 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2603 $wgOut->addWikiMsg( 'confirmdeletetext' );
2604
2605 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2606 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2607 <td></td>
2608 <td class='mw-input'><strong>" .
2609 Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
2610 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2611 "</strong></td>
2612 </tr>";
2613 } else {
2614 $suppress = '';
2615 }
2616 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
2617
2618 $form = Xml::openElement( 'form', array( 'method' => 'post',
2619 'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2620 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2621 Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2622 Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2623 "<tr id=\"wpDeleteReasonListRow\">
2624 <td class='mw-label'>" .
2625 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2626 "</td>
2627 <td class='mw-input'>" .
2628 Xml::listDropDown( 'wpDeleteReasonList',
2629 wfMsgForContent( 'deletereason-dropdown' ),
2630 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2631 "</td>
2632 </tr>
2633 <tr id=\"wpDeleteReasonRow\">
2634 <td class='mw-label'>" .
2635 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2636 "</td>
2637 <td class='mw-input'>" .
2638 Xml::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255',
2639 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2640 "</td>
2641 </tr>
2642 <tr>
2643 <td></td>
2644 <td class='mw-input'>" .
2645 Xml::checkLabel( wfMsg( 'watchthis' ),
2646 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2647 "</td>
2648 </tr>
2649 $suppress
2650 <tr>
2651 <td></td>
2652 <td class='mw-submit'>" .
2653 Xml::submitButton( wfMsg( 'deletepage' ),
2654 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2655 "</td>
2656 </tr>" .
2657 Xml::closeElement( 'table' ) .
2658 Xml::closeElement( 'fieldset' ) .
2659 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
2660 Xml::closeElement( 'form' );
2661
2662 if( $wgUser->isAllowed( 'editinterface' ) ) {
2663 $skin = $wgUser->getSkin();
2664 $title = Title::makeTitle( NS_MEDIAWIKI, 'Deletereason-dropdown' );
2665 $link = $skin->link(
2666 $title,
2667 wfMsgHtml( 'delete-edit-reasonlist' ),
2668 array(),
2669 array( 'action' => 'edit' )
2670 );
2671 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2672 }
2673
2674 $wgOut->addHTML( $form );
2675 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2676 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2677 }
2678
2679 /**
2680 * Perform a deletion and output success or failure messages
2681 */
2682 public function doDelete( $reason, $suppress = false ) {
2683 global $wgOut, $wgUser;
2684 $id = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2685
2686 $error = '';
2687 if( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2688 if( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2689 $deleted = $this->mTitle->getPrefixedText();
2690
2691 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2692 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2693
2694 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2695
2696 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2697 $wgOut->returnToMain( false );
2698 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2699 } else {
2700 if( $error == '' ) {
2701 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2702 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2703 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2704 } else {
2705 $wgOut->showFatalError( $error );
2706 }
2707 }
2708 }
2709 }
2710
2711 /**
2712 * Back-end article deletion
2713 * Deletes the article with database consistency, writes logs, purges caches
2714 * Returns success
2715 */
2716 public function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2717 global $wgUseSquid, $wgDeferredUpdateList;
2718 global $wgUseTrackbacks;
2719
2720 wfDebug( __METHOD__."\n" );
2721
2722 $dbw = wfGetDB( DB_MASTER );
2723 $ns = $this->mTitle->getNamespace();
2724 $t = $this->mTitle->getDBkey();
2725 $id = $id ? $id : $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2726
2727 if( $t == '' || $id == 0 ) {
2728 return false;
2729 }
2730
2731 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getRawText() ), -1 );
2732 array_push( $wgDeferredUpdateList, $u );
2733
2734 // Bitfields to further suppress the content
2735 if( $suppress ) {
2736 $bitfield = 0;
2737 // This should be 15...
2738 $bitfield |= Revision::DELETED_TEXT;
2739 $bitfield |= Revision::DELETED_COMMENT;
2740 $bitfield |= Revision::DELETED_USER;
2741 $bitfield |= Revision::DELETED_RESTRICTED;
2742 } else {
2743 $bitfield = 'rev_deleted';
2744 }
2745
2746 $dbw->begin();
2747 // For now, shunt the revision data into the archive table.
2748 // Text is *not* removed from the text table; bulk storage
2749 // is left intact to avoid breaking block-compression or
2750 // immutable storage schemes.
2751 //
2752 // For backwards compatibility, note that some older archive
2753 // table entries will have ar_text and ar_flags fields still.
2754 //
2755 // In the future, we may keep revisions and mark them with
2756 // the rev_deleted field, which is reserved for this purpose.
2757 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2758 array(
2759 'ar_namespace' => 'page_namespace',
2760 'ar_title' => 'page_title',
2761 'ar_comment' => 'rev_comment',
2762 'ar_user' => 'rev_user',
2763 'ar_user_text' => 'rev_user_text',
2764 'ar_timestamp' => 'rev_timestamp',
2765 'ar_minor_edit' => 'rev_minor_edit',
2766 'ar_rev_id' => 'rev_id',
2767 'ar_text_id' => 'rev_text_id',
2768 'ar_text' => '\'\'', // Be explicit to appease
2769 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2770 'ar_len' => 'rev_len',
2771 'ar_page_id' => 'page_id',
2772 'ar_deleted' => $bitfield
2773 ), array(
2774 'page_id' => $id,
2775 'page_id = rev_page'
2776 ), __METHOD__
2777 );
2778
2779 # Delete restrictions for it
2780 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2781
2782 # Now that it's safely backed up, delete it
2783 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2784 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2785 if( !$ok ) {
2786 $dbw->rollback();
2787 return false;
2788 }
2789
2790 # Fix category table counts
2791 $cats = array();
2792 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
2793 foreach( $res as $row ) {
2794 $cats []= $row->cl_to;
2795 }
2796 $this->updateCategoryCounts( array(), $cats );
2797
2798 # If using cascading deletes, we can skip some explicit deletes
2799 if( !$dbw->cascadingDeletes() ) {
2800 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2801
2802 if($wgUseTrackbacks)
2803 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2804
2805 # Delete outgoing links
2806 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2807 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2808 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2809 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2810 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2811 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2812 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2813 }
2814
2815 # If using cleanup triggers, we can skip some manual deletes
2816 if( !$dbw->cleanupTriggers() ) {
2817 # Clean up recentchanges entries...
2818 $dbw->delete( 'recentchanges',
2819 array( 'rc_type != '.RC_LOG,
2820 'rc_namespace' => $this->mTitle->getNamespace(),
2821 'rc_title' => $this->mTitle->getDBkey() ),
2822 __METHOD__ );
2823 $dbw->delete( 'recentchanges',
2824 array( 'rc_type != '.RC_LOG, 'rc_cur_id' => $id ),
2825 __METHOD__ );
2826 }
2827
2828 # Clear caches
2829 Article::onArticleDelete( $this->mTitle );
2830
2831 # Clear the cached article id so the interface doesn't act like we exist
2832 $this->mTitle->resetArticleID( 0 );
2833
2834 # Log the deletion, if the page was suppressed, log it at Oversight instead
2835 $logtype = $suppress ? 'suppress' : 'delete';
2836 $log = new LogPage( $logtype );
2837
2838 # Make sure logging got through
2839 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
2840
2841 $dbw->commit();
2842
2843 return true;
2844 }
2845
2846 /**
2847 * Roll back the most recent consecutive set of edits to a page
2848 * from the same user; fails if there are no eligible edits to
2849 * roll back to, e.g. user is the sole contributor. This function
2850 * performs permissions checks on $wgUser, then calls commitRollback()
2851 * to do the dirty work
2852 *
2853 * @param $fromP String: Name of the user whose edits to rollback.
2854 * @param $summary String: Custom summary. Set to default summary if empty.
2855 * @param $token String: Rollback token.
2856 * @param $bot Boolean: If true, mark all reverted edits as bot.
2857 *
2858 * @param $resultDetails Array: contains result-specific array of additional values
2859 * 'alreadyrolled' : 'current' (rev)
2860 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2861 *
2862 * @return array of errors, each error formatted as
2863 * array(messagekey, param1, param2, ...).
2864 * On success, the array is empty. This array can also be passed to
2865 * OutputPage::showPermissionsErrorPage().
2866 */
2867 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2868 global $wgUser;
2869 $resultDetails = null;
2870
2871 # Check permissions
2872 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
2873 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser );
2874 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2875
2876 if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
2877 $errors[] = array( 'sessionfailure' );
2878
2879 if( $wgUser->pingLimiter( 'rollback' ) || $wgUser->pingLimiter() ) {
2880 $errors[] = array( 'actionthrottledtext' );
2881 }
2882 # If there were errors, bail out now
2883 if( !empty( $errors ) )
2884 return $errors;
2885
2886 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2887 }
2888
2889 /**
2890 * Backend implementation of doRollback(), please refer there for parameter
2891 * and return value documentation
2892 *
2893 * NOTE: This function does NOT check ANY permissions, it just commits the
2894 * rollback to the DB Therefore, you should only call this function direct-
2895 * ly if you want to use custom permissions checks. If you don't, use
2896 * doRollback() instead.
2897 */
2898 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2899 global $wgUseRCPatrol, $wgUser, $wgLang;
2900 $dbw = wfGetDB( DB_MASTER );
2901
2902 if( wfReadOnly() ) {
2903 return array( array( 'readonlytext' ) );
2904 }
2905
2906 # Get the last editor
2907 $current = Revision::newFromTitle( $this->mTitle );
2908 if( is_null( $current ) ) {
2909 # Something wrong... no page?
2910 return array(array('notanarticle'));
2911 }
2912
2913 $from = str_replace( '_', ' ', $fromP );
2914 if( $from != $current->getUserText() ) {
2915 $resultDetails = array( 'current' => $current );
2916 return array(array('alreadyrolled',
2917 htmlspecialchars($this->mTitle->getPrefixedText()),
2918 htmlspecialchars($fromP),
2919 htmlspecialchars($current->getUserText())
2920 ));
2921 }
2922
2923 # Get the last edit not by this guy
2924 $user = intval( $current->getUser() );
2925 $user_text = $dbw->addQuotes( $current->getUserText() );
2926 $s = $dbw->selectRow( 'revision',
2927 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2928 array( 'rev_page' => $current->getPage(),
2929 "rev_user != {$user} OR rev_user_text != {$user_text}"
2930 ), __METHOD__,
2931 array( 'USE INDEX' => 'page_timestamp',
2932 'ORDER BY' => 'rev_timestamp DESC' )
2933 );
2934 if( $s === false ) {
2935 # No one else ever edited this page
2936 return array(array('cantrollback'));
2937 } else if( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
2938 # Only admins can see this text
2939 return array(array('notvisiblerev'));
2940 }
2941
2942 $set = array();
2943 if( $bot && $wgUser->isAllowed('markbotedits') ) {
2944 # Mark all reverted edits as bot
2945 $set['rc_bot'] = 1;
2946 }
2947 if( $wgUseRCPatrol ) {
2948 # Mark all reverted edits as patrolled
2949 $set['rc_patrolled'] = 1;
2950 }
2951
2952 if( $set ) {
2953 $dbw->update( 'recentchanges', $set,
2954 array( /* WHERE */
2955 'rc_cur_id' => $current->getPage(),
2956 'rc_user_text' => $current->getUserText(),
2957 "rc_timestamp > '{$s->rev_timestamp}'",
2958 ), __METHOD__
2959 );
2960 }
2961
2962 # Generate the edit summary if necessary
2963 $target = Revision::newFromId( $s->rev_id );
2964 if( empty( $summary ) ){
2965 $summary = wfMsgForContent( 'revertpage' );
2966 }
2967
2968 # Allow the custom summary to use the same args as the default message
2969 $args = array(
2970 $target->getUserText(), $from, $s->rev_id,
2971 $wgLang->timeanddate(wfTimestamp(TS_MW, $s->rev_timestamp), true),
2972 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2973 );
2974 $summary = wfMsgReplaceArgs( $summary, $args );
2975
2976 # Save
2977 $flags = EDIT_UPDATE;
2978
2979 if( $wgUser->isAllowed('minoredit') )
2980 $flags |= EDIT_MINOR;
2981
2982 if( $bot && ($wgUser->isAllowed('markbotedits') || $wgUser->isAllowed('bot')) )
2983 $flags |= EDIT_FORCE_BOT;
2984 # Actually store the edit
2985 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2986 if( !empty( $status->value['revision'] ) ) {
2987 $revId = $status->value['revision']->getId();
2988 } else {
2989 $revId = false;
2990 }
2991
2992 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
2993
2994 $resultDetails = array(
2995 'summary' => $summary,
2996 'current' => $current,
2997 'target' => $target,
2998 'newid' => $revId
2999 );
3000 return array();
3001 }
3002
3003 /**
3004 * User interface for rollback operations
3005 */
3006 public function rollback() {
3007 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
3008 $details = null;
3009
3010 $result = $this->doRollback(
3011 $wgRequest->getVal( 'from' ),
3012 $wgRequest->getText( 'summary' ),
3013 $wgRequest->getVal( 'token' ),
3014 $wgRequest->getBool( 'bot' ),
3015 $details
3016 );
3017
3018 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
3019 $wgOut->rateLimited();
3020 return;
3021 }
3022 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ) {
3023 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3024 $errArray = $result[0];
3025 $errMsg = array_shift( $errArray );
3026 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3027 if( isset( $details['current'] ) ){
3028 $current = $details['current'];
3029 if( $current->getComment() != '' ) {
3030 $wgOut->addWikiMsgArray( 'editcomment', array(
3031 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3032 }
3033 }
3034 return;
3035 }
3036 # Display permissions errors before read-only message -- there's no
3037 # point in misleading the user into thinking the inability to rollback
3038 # is only temporary.
3039 if( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3040 # array_diff is completely broken for arrays of arrays, sigh. Re-
3041 # move any 'readonlytext' error manually.
3042 $out = array();
3043 foreach( $result as $error ) {
3044 if( $error != array( 'readonlytext' ) ) {
3045 $out []= $error;
3046 }
3047 }
3048 $wgOut->showPermissionsErrorPage( $out );
3049 return;
3050 }
3051 if( $result == array( array( 'readonlytext' ) ) ) {
3052 $wgOut->readOnlyPage();
3053 return;
3054 }
3055
3056 $current = $details['current'];
3057 $target = $details['target'];
3058 $newId = $details['newid'];
3059 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3060 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3061 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
3062 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
3063 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
3064 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
3065 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3066 $wgOut->returnToMain( false, $this->mTitle );
3067
3068 if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3069 $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true );
3070 $de->showDiff( '', '' );
3071 }
3072 }
3073
3074
3075 /**
3076 * Do standard deferred updates after page view
3077 */
3078 public function viewUpdates() {
3079 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3080 # Don't update page view counters on views from bot users (bug 14044)
3081 if( !$wgDisableCounters && !$wgUser->isAllowed('bot') && $this->getID() ) {
3082 Article::incViewCount( $this->getID() );
3083 $u = new SiteStatsUpdate( 1, 0, 0 );
3084 array_push( $wgDeferredUpdateList, $u );
3085 }
3086 # Update newtalk / watchlist notification status
3087 $wgUser->clearNotification( $this->mTitle );
3088 }
3089
3090 /**
3091 * Prepare text which is about to be saved.
3092 * Returns a stdclass with source, pst and output members
3093 */
3094 public function prepareTextForEdit( $text, $revid=null ) {
3095 if( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid) {
3096 // Already prepared
3097 return $this->mPreparedEdit;
3098 }
3099 global $wgParser;
3100 $edit = (object)array();
3101 $edit->revid = $revid;
3102 $edit->newText = $text;
3103 $edit->pst = $this->preSaveTransform( $text );
3104 $options = $this->getParserOptions();
3105 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
3106 $edit->oldText = $this->getContent();
3107 $this->mPreparedEdit = $edit;
3108 return $edit;
3109 }
3110
3111 /**
3112 * Do standard deferred updates after page edit.
3113 * Update links tables, site stats, search index and message cache.
3114 * Purges pages that include this page if the text was changed here.
3115 * Every 100th edit, prune the recent changes table.
3116 *
3117 * @private
3118 * @param $text New text of the article
3119 * @param $summary Edit summary
3120 * @param $minoredit Minor edit
3121 * @param $timestamp_of_pagechange Timestamp associated with the page change
3122 * @param $newid rev_id value of the new revision
3123 * @param $changed Whether or not the content actually changed
3124 */
3125 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
3126 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
3127
3128 wfProfileIn( __METHOD__ );
3129
3130 # Parse the text
3131 # Be careful not to double-PST: $text is usually already PST-ed once
3132 if( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
3133 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
3134 $editInfo = $this->prepareTextForEdit( $text, $newid );
3135 } else {
3136 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
3137 $editInfo = $this->mPreparedEdit;
3138 }
3139
3140 # Save it to the parser cache
3141 if( $wgEnableParserCache ) {
3142 $popts = $this->getParserOptions();
3143 $parserCache = ParserCache::singleton();
3144 $parserCache->save( $editInfo->output, $this, $popts );
3145 }
3146
3147 # Update the links tables
3148 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
3149 $u->doUpdate();
3150
3151 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3152
3153 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3154 if( 0 == mt_rand( 0, 99 ) ) {
3155 // Flush old entries from the `recentchanges` table; we do this on
3156 // random requests so as to avoid an increase in writes for no good reason
3157 global $wgRCMaxAge;
3158 $dbw = wfGetDB( DB_MASTER );
3159 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3160 $recentchanges = $dbw->tableName( 'recentchanges' );
3161 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
3162 $dbw->query( $sql );
3163 }
3164 }
3165
3166 $id = $this->getID();
3167 $title = $this->mTitle->getPrefixedDBkey();
3168 $shortTitle = $this->mTitle->getDBkey();
3169
3170 if( 0 == $id ) {
3171 wfProfileOut( __METHOD__ );
3172 return;
3173 }
3174
3175 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
3176 array_push( $wgDeferredUpdateList, $u );
3177 $u = new SearchUpdate( $id, $title, $text );
3178 array_push( $wgDeferredUpdateList, $u );
3179
3180 # If this is another user's talk page, update newtalk
3181 # Don't do this if $changed = false otherwise some idiot can null-edit a
3182 # load of user talk pages and piss people off, nor if it's a minor edit
3183 # by a properly-flagged bot.
3184 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
3185 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
3186 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3187 $other = User::newFromName( $shortTitle, false );
3188 if( !$other ) {
3189 wfDebug( __METHOD__.": invalid username\n" );
3190 } elseif( User::isIP( $shortTitle ) ) {
3191 // An anonymous user
3192 $other->setNewtalk( true );
3193 } elseif( $other->isLoggedIn() ) {
3194 $other->setNewtalk( true );
3195 } else {
3196 wfDebug( __METHOD__. ": don't need to notify a nonexistent user\n" );
3197 }
3198 }
3199 }
3200
3201 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3202 $wgMessageCache->replace( $shortTitle, $text );
3203 }
3204
3205 wfProfileOut( __METHOD__ );
3206 }
3207
3208 /**
3209 * Perform article updates on a special page creation.
3210 *
3211 * @param $rev Revision object
3212 *
3213 * @todo This is a shitty interface function. Kill it and replace the
3214 * other shitty functions like editUpdates and such so it's not needed
3215 * anymore.
3216 */
3217 public function createUpdates( $rev ) {
3218 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
3219 $this->mTotalAdjustment = 1;
3220 $this->editUpdates( $rev->getText(), $rev->getComment(),
3221 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3222 }
3223
3224 /**
3225 * Generate the navigation links when browsing through an article revisions
3226 * It shows the information as:
3227 * Revision as of \<date\>; view current revision
3228 * \<- Previous version | Next Version -\>
3229 *
3230 * @param $oldid String: revision ID of this article revision
3231 */
3232 public function setOldSubtitle( $oldid = 0 ) {
3233 global $wgLang, $wgOut, $wgUser, $wgRequest;
3234
3235 if( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3236 return;
3237 }
3238
3239 $revision = Revision::newFromId( $oldid );
3240
3241 $current = ( $oldid == $this->mLatest );
3242 $td = $wgLang->timeanddate( $this->mTimestamp, true );
3243 $tddate = $wgLang->date( $this->mTimestamp, true );
3244 $tdtime = $wgLang->time( $this->mTimestamp, true );
3245 $sk = $wgUser->getSkin();
3246 $lnk = $current
3247 ? wfMsgHtml( 'currentrevisionlink' )
3248 : $sk->link(
3249 $this->mTitle,
3250 wfMsgHtml( 'currentrevisionlink' ),
3251 array(),
3252 array(),
3253 array( 'known', 'noclasses' )
3254 );
3255 $curdiff = $current
3256 ? wfMsgHtml( 'diff' )
3257 : $sk->link(
3258 $this->mTitle,
3259 wfMsgHtml( 'diff' ),
3260 array(),
3261 array(
3262 'diff' => 'cur',
3263 'oldid' => $oldid
3264 ),
3265 array( 'known', 'noclasses' )
3266 );
3267 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
3268 $prevlink = $prev
3269 ? $sk->link(
3270 $this->mTitle,
3271 wfMsgHtml( 'previousrevision' ),
3272 array(),
3273 array(
3274 'direction' => 'prev',
3275 'oldid' => $oldid
3276 ),
3277 array( 'known', 'noclasses' )
3278 )
3279 : wfMsgHtml( 'previousrevision' );
3280 $prevdiff = $prev
3281 ? $sk->link(
3282 $this->mTitle,
3283 wfMsgHtml( 'diff' ),
3284 array(),
3285 array(
3286 'diff' => 'prev',
3287 'oldid' => $oldid
3288 ),
3289 array( 'known', 'noclasses' )
3290 )
3291 : wfMsgHtml( 'diff' );
3292 $nextlink = $current
3293 ? wfMsgHtml( 'nextrevision' )
3294 : $sk->link(
3295 $this->mTitle,
3296 wfMsgHtml( 'nextrevision' ),
3297 array(),
3298 array(
3299 'direction' => 'next',
3300 'oldid' => $oldid
3301 ),
3302 array( 'known', 'noclasses' )
3303 );
3304 $nextdiff = $current
3305 ? wfMsgHtml( 'diff' )
3306 : $sk->link(
3307 $this->mTitle,
3308 wfMsgHtml( 'diff' ),
3309 array(),
3310 array(
3311 'diff' => 'next',
3312 'oldid' => $oldid
3313 ),
3314 array( 'known', 'noclasses' )
3315 );
3316
3317 $cdel='';
3318 if( $wgUser->isAllowed( 'deleterevision' ) ) {
3319 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
3320 if( $revision->isCurrent() ) {
3321 // We don't handle top deleted edits too well
3322 $cdel = wfMsgHtml( 'rev-delundel' );
3323 } else if( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
3324 // If revision was hidden from sysops
3325 $cdel = wfMsgHtml( 'rev-delundel' );
3326 } else {
3327 $cdel = $sk->link(
3328 $revdel,
3329 wfMsgHtml('rev-delundel'),
3330 array(),
3331 array(
3332 'type' => 'revision',
3333 'target' => urlencode( $this->mTitle->getPrefixedDbkey() ),
3334 'ids' => urlencode( $oldid )
3335 ),
3336 array( 'known', 'noclasses' )
3337 );
3338 // Bolden oversighted content
3339 if( $revision->isDeleted( Revision::DELETED_RESTRICTED ) )
3340 $cdel = "<strong>$cdel</strong>";
3341 }
3342 $cdel = "(<small>$cdel</small>) ";
3343 }
3344 $unhide = $wgRequest->getInt('unhide') == 1 && $wgUser->matchEditToken( $wgRequest->getVal('token'), $oldid );
3345 # Show user links if allowed to see them. If hidden, then show them only if requested...
3346 $userlinks = $sk->revUserTools( $revision, !$unhide );
3347
3348 $m = wfMsg( 'revision-info-current' );
3349 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
3350 ? 'revision-info-current'
3351 : 'revision-info';
3352
3353 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3354 wfMsgExt(
3355 $infomsg,
3356 array( 'parseinline', 'replaceafter' ),
3357 $td,
3358 $userlinks,
3359 $revision->getID(),
3360 $tddate,
3361 $tdtime
3362 ) .
3363 "</div>\n" .
3364 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3365 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3366 $wgOut->setSubtitle( $r );
3367 }
3368
3369 /**
3370 * This function is called right before saving the wikitext,
3371 * so we can do things like signatures and links-in-context.
3372 *
3373 * @param $text String
3374 */
3375 public function preSaveTransform( $text ) {
3376 global $wgParser, $wgUser;
3377 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
3378 }
3379
3380 /* Caching functions */
3381
3382 /**
3383 * checkLastModified returns true if it has taken care of all
3384 * output to the client that is necessary for this request.
3385 * (that is, it has sent a cached version of the page)
3386 */
3387 protected function tryFileCache() {
3388 static $called = false;
3389 if( $called ) {
3390 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3391 return false;
3392 }
3393 $called = true;
3394 if( $this->isFileCacheable() ) {
3395 $cache = new HTMLFileCache( $this->mTitle );
3396 if( $cache->isFileCacheGood( $this->mTouched ) ) {
3397 wfDebug( "Article::tryFileCache(): about to load file\n" );
3398 $cache->loadFromFileCache();
3399 return true;
3400 } else {
3401 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3402 ob_start( array(&$cache, 'saveToFileCache' ) );
3403 }
3404 } else {
3405 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3406 }
3407 return false;
3408 }
3409
3410 /**
3411 * Check if the page can be cached
3412 * @return bool
3413 */
3414 public function isFileCacheable() {
3415 $cacheable = false;
3416 if( HTMLFileCache::useFileCache() ) {
3417 $cacheable = $this->getID() && !$this->mRedirectedFrom;
3418 // Extension may have reason to disable file caching on some pages.
3419 if( $cacheable ) {
3420 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3421 }
3422 }
3423 return $cacheable;
3424 }
3425
3426 /**
3427 * Loads page_touched and returns a value indicating if it should be used
3428 *
3429 */
3430 public function checkTouched() {
3431 if( !$this->mDataLoaded ) {
3432 $this->loadPageData();
3433 }
3434 return !$this->mIsRedirect;
3435 }
3436
3437 /**
3438 * Get the page_touched field
3439 */
3440 public function getTouched() {
3441 # Ensure that page data has been loaded
3442 if( !$this->mDataLoaded ) {
3443 $this->loadPageData();
3444 }
3445 return $this->mTouched;
3446 }
3447
3448 /**
3449 * Get the page_latest field
3450 */
3451 public function getLatest() {
3452 if( !$this->mDataLoaded ) {
3453 $this->loadPageData();
3454 }
3455 return (int)$this->mLatest;
3456 }
3457
3458 /**
3459 * Edit an article without doing all that other stuff
3460 * The article must already exist; link tables etc
3461 * are not updated, caches are not flushed.
3462 *
3463 * @param $text String: text submitted
3464 * @param $comment String: comment submitted
3465 * @param $minor Boolean: whereas it's a minor modification
3466 */
3467 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3468 wfProfileIn( __METHOD__ );
3469
3470 $dbw = wfGetDB( DB_MASTER );
3471 $revision = new Revision( array(
3472 'page' => $this->getId(),
3473 'text' => $text,
3474 'comment' => $comment,
3475 'minor_edit' => $minor ? 1 : 0,
3476 ) );
3477 $revision->insertOn( $dbw );
3478 $this->updateRevisionOn( $dbw, $revision );
3479
3480 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $wgUser) );
3481
3482 wfProfileOut( __METHOD__ );
3483 }
3484
3485 /**
3486 * Used to increment the view counter
3487 *
3488 * @param $id Integer: article id
3489 */
3490 public static function incViewCount( $id ) {
3491 $id = intval( $id );
3492 global $wgHitcounterUpdateFreq, $wgDBtype;
3493
3494 $dbw = wfGetDB( DB_MASTER );
3495 $pageTable = $dbw->tableName( 'page' );
3496 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3497 $acchitsTable = $dbw->tableName( 'acchits' );
3498
3499 if( $wgHitcounterUpdateFreq <= 1 ) {
3500 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3501 return;
3502 }
3503
3504 # Not important enough to warrant an error page in case of failure
3505 $oldignore = $dbw->ignoreErrors( true );
3506
3507 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3508
3509 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
3510 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3511 # Most of the time (or on SQL errors), skip row count check
3512 $dbw->ignoreErrors( $oldignore );
3513 return;
3514 }
3515
3516 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3517 $row = $dbw->fetchObject( $res );
3518 $rown = intval( $row->n );
3519 if( $rown >= $wgHitcounterUpdateFreq ){
3520 wfProfileIn( 'Article::incViewCount-collect' );
3521 $old_user_abort = ignore_user_abort( true );
3522
3523 if($wgDBtype == 'mysql')
3524 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3525 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
3526 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3527 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3528 'GROUP BY hc_id');
3529 $dbw->query("DELETE FROM $hitcounterTable");
3530 if($wgDBtype == 'mysql') {
3531 $dbw->query('UNLOCK TABLES');
3532 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3533 'WHERE page_id = hc_id');
3534 }
3535 else {
3536 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3537 "FROM $acchitsTable WHERE page_id = hc_id");
3538 }
3539 $dbw->query("DROP TABLE $acchitsTable");
3540
3541 ignore_user_abort( $old_user_abort );
3542 wfProfileOut( 'Article::incViewCount-collect' );
3543 }
3544 $dbw->ignoreErrors( $oldignore );
3545 }
3546
3547 /**#@+
3548 * The onArticle*() functions are supposed to be a kind of hooks
3549 * which should be called whenever any of the specified actions
3550 * are done.
3551 *
3552 * This is a good place to put code to clear caches, for instance.
3553 *
3554 * This is called on page move and undelete, as well as edit
3555 *
3556 * @param $title a title object
3557 */
3558
3559 public static function onArticleCreate( $title ) {
3560 # Update existence markers on article/talk tabs...
3561 if( $title->isTalkPage() ) {
3562 $other = $title->getSubjectPage();
3563 } else {
3564 $other = $title->getTalkPage();
3565 }
3566 $other->invalidateCache();
3567 $other->purgeSquid();
3568
3569 $title->touchLinks();
3570 $title->purgeSquid();
3571 $title->deleteTitleProtection();
3572 }
3573
3574 public static function onArticleDelete( $title ) {
3575 global $wgMessageCache;
3576 # Update existence markers on article/talk tabs...
3577 if( $title->isTalkPage() ) {
3578 $other = $title->getSubjectPage();
3579 } else {
3580 $other = $title->getTalkPage();
3581 }
3582 $other->invalidateCache();
3583 $other->purgeSquid();
3584
3585 $title->touchLinks();
3586 $title->purgeSquid();
3587
3588 # File cache
3589 HTMLFileCache::clearFileCache( $title );
3590
3591 # Messages
3592 if( $title->getNamespace() == NS_MEDIAWIKI ) {
3593 $wgMessageCache->replace( $title->getDBkey(), false );
3594 }
3595 # Images
3596 if( $title->getNamespace() == NS_FILE ) {
3597 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3598 $update->doUpdate();
3599 }
3600 # User talk pages
3601 if( $title->getNamespace() == NS_USER_TALK ) {
3602 $user = User::newFromName( $title->getText(), false );
3603 $user->setNewtalk( false );
3604 }
3605 # Image redirects
3606 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3607 }
3608
3609 /**
3610 * Purge caches on page update etc
3611 */
3612 public static function onArticleEdit( $title, $flags = '' ) {
3613 global $wgDeferredUpdateList;
3614
3615 // Invalidate caches of articles which include this page
3616 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3617
3618 // Invalidate the caches of all pages which redirect here
3619 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3620
3621 # Purge squid for this page only
3622 $title->purgeSquid();
3623
3624 # Clear file cache for this page only
3625 HTMLFileCache::clearFileCache( $title );
3626 }
3627
3628 /**#@-*/
3629
3630 /**
3631 * Overriden by ImagePage class, only present here to avoid a fatal error
3632 * Called for ?action=revert
3633 */
3634 public function revert() {
3635 global $wgOut;
3636 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3637 }
3638
3639 /**
3640 * Info about this page
3641 * Called for ?action=info when $wgAllowPageInfo is on.
3642 */
3643 public function info() {
3644 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3645
3646 if( !$wgAllowPageInfo ) {
3647 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3648 return;
3649 }
3650
3651 $page = $this->mTitle->getSubjectPage();
3652
3653 $wgOut->setPagetitle( $page->getPrefixedText() );
3654 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3655 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3656
3657 if( !$this->mTitle->exists() ) {
3658 $wgOut->addHTML( '<div class="noarticletext">' );
3659 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3660 // This doesn't quite make sense; the user is asking for
3661 // information about the _page_, not the message... -- RC
3662 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
3663 } else {
3664 $msg = $wgUser->isLoggedIn()
3665 ? 'noarticletext'
3666 : 'noarticletextanon';
3667 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3668 }
3669 $wgOut->addHTML( '</div>' );
3670 } else {
3671 $dbr = wfGetDB( DB_SLAVE );
3672 $wl_clause = array(
3673 'wl_title' => $page->getDBkey(),
3674 'wl_namespace' => $page->getNamespace() );
3675 $numwatchers = $dbr->selectField(
3676 'watchlist',
3677 'COUNT(*)',
3678 $wl_clause,
3679 __METHOD__,
3680 $this->getSelectOptions() );
3681
3682 $pageInfo = $this->pageCountInfo( $page );
3683 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3684
3685 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3686 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3687 if( $talkInfo ) {
3688 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3689 }
3690 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3691 if( $talkInfo ) {
3692 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3693 }
3694 $wgOut->addHTML( '</ul>' );
3695 }
3696 }
3697
3698 /**
3699 * Return the total number of edits and number of unique editors
3700 * on a given page. If page does not exist, returns false.
3701 *
3702 * @param $title Title object
3703 * @return array
3704 */
3705 public function pageCountInfo( $title ) {
3706 $id = $title->getArticleId();
3707 if( $id == 0 ) {
3708 return false;
3709 }
3710 $dbr = wfGetDB( DB_SLAVE );
3711 $rev_clause = array( 'rev_page' => $id );
3712 $edits = $dbr->selectField(
3713 'revision',
3714 'COUNT(rev_page)',
3715 $rev_clause,
3716 __METHOD__,
3717 $this->getSelectOptions()
3718 );
3719 $authors = $dbr->selectField(
3720 'revision',
3721 'COUNT(DISTINCT rev_user_text)',
3722 $rev_clause,
3723 __METHOD__,
3724 $this->getSelectOptions()
3725 );
3726 return array( 'edits' => $edits, 'authors' => $authors );
3727 }
3728
3729 /**
3730 * Return a list of templates used by this article.
3731 * Uses the templatelinks table
3732 *
3733 * @return Array of Title objects
3734 */
3735 public function getUsedTemplates() {
3736 $result = array();
3737 $id = $this->mTitle->getArticleID();
3738 if( $id == 0 ) {
3739 return array();
3740 }
3741 $dbr = wfGetDB( DB_SLAVE );
3742 $res = $dbr->select( array( 'templatelinks' ),
3743 array( 'tl_namespace', 'tl_title' ),
3744 array( 'tl_from' => $id ),
3745 __METHOD__ );
3746 if( $res !== false ) {
3747 foreach( $res as $row ) {
3748 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
3749 }
3750 }
3751 $dbr->freeResult( $res );
3752 return $result;
3753 }
3754
3755 /**
3756 * Returns a list of hidden categories this page is a member of.
3757 * Uses the page_props and categorylinks tables.
3758 *
3759 * @return Array of Title objects
3760 */
3761 public function getHiddenCategories() {
3762 $result = array();
3763 $id = $this->mTitle->getArticleID();
3764 if( $id == 0 ) {
3765 return array();
3766 }
3767 $dbr = wfGetDB( DB_SLAVE );
3768 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3769 array( 'cl_to' ),
3770 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3771 'page_namespace' => NS_CATEGORY, 'page_title=cl_to'),
3772 __METHOD__ );
3773 if( $res !== false ) {
3774 foreach( $res as $row ) {
3775 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3776 }
3777 }
3778 $dbr->freeResult( $res );
3779 return $result;
3780 }
3781
3782 /**
3783 * Return an applicable autosummary if one exists for the given edit.
3784 * @param $oldtext String: the previous text of the page.
3785 * @param $newtext String: The submitted text of the page.
3786 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
3787 * @return string An appropriate autosummary, or an empty string.
3788 */
3789 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3790 # Decide what kind of autosummary is needed.
3791
3792 # Redirect autosummaries
3793 $ot = Title::newFromRedirect( $oldtext );
3794 $rt = Title::newFromRedirect( $newtext );
3795 if( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
3796 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3797 }
3798
3799 # New page autosummaries
3800 if( $flags & EDIT_NEW && strlen( $newtext ) ) {
3801 # If they're making a new article, give its text, truncated, in the summary.
3802 global $wgContLang;
3803 $truncatedtext = $wgContLang->truncate(
3804 str_replace("\n", ' ', $newtext),
3805 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
3806 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3807 }
3808
3809 # Blanking autosummaries
3810 if( $oldtext != '' && $newtext == '' ) {
3811 return wfMsgForContent( 'autosumm-blank' );
3812 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3813 # Removing more than 90% of the article
3814 global $wgContLang;
3815 $truncatedtext = $wgContLang->truncate(
3816 $newtext,
3817 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
3818 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3819 }
3820
3821 # If we reach this point, there's no applicable autosummary for our case, so our
3822 # autosummary is empty.
3823 return '';
3824 }
3825
3826 /**
3827 * Add the primary page-view wikitext to the output buffer
3828 * Saves the text into the parser cache if possible.
3829 * Updates templatelinks if it is out of date.
3830 *
3831 * @param $text String
3832 * @param $cache Boolean
3833 */
3834 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
3835 global $wgOut;
3836
3837 $parserOutput = $this->getOutputFromWikitext( $text, $cache, $parserOptions );
3838 $wgOut->addParserOutput( $parserOutput );
3839 }
3840
3841 /**
3842 * This does all the heavy lifting for outputWikitext, except it returns the parser
3843 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
3844 * say, embedding thread pages within a discussion system (LiquidThreads)
3845 */
3846 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
3847 global $wgParser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
3848
3849 if ( !$parserOptions ) {
3850 $parserOptions = $this->getParserOptions();
3851 }
3852
3853 $time = -wfTime();
3854 $parserOutput = $wgParser->parse( $text, $this->mTitle,
3855 $parserOptions, true, true, $this->getRevIdFetched() );
3856 $time += wfTime();
3857
3858 # Timing hack
3859 if( $time > 3 ) {
3860 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3861 $this->mTitle->getPrefixedDBkey()));
3862 }
3863
3864 if( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3865 $parserCache = ParserCache::singleton();
3866 $parserCache->save( $parserOutput, $this, $parserOptions );
3867 }
3868 // Make sure file cache is not used on uncacheable content.
3869 // Output that has magic words in it can still use the parser cache
3870 // (if enabled), though it will generally expire sooner.
3871 if( $parserOutput->getCacheTime() == -1 || $parserOutput->containsOldMagic() ) {
3872 $wgUseFileCache = false;
3873 }
3874 $this->doCascadeProtectionUpdates( $parserOutput );
3875 return $parserOutput;
3876 }
3877
3878 /**
3879 * Get parser options suitable for rendering the primary article wikitext
3880 */
3881 public function getParserOptions() {
3882 global $wgUser;
3883 if ( !$this->mParserOptions ) {
3884 $this->mParserOptions = new ParserOptions( $wgUser );
3885 $this->mParserOptions->setTidy( true );
3886 $this->mParserOptions->enableLimitReport();
3887 }
3888 return $this->mParserOptions;
3889 }
3890
3891 protected function doCascadeProtectionUpdates( $parserOutput ) {
3892 if( !$this->isCurrent() || wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
3893 return;
3894 }
3895
3896 // templatelinks table may have become out of sync,
3897 // especially if using variable-based transclusions.
3898 // For paranoia, check if things have changed and if
3899 // so apply updates to the database. This will ensure
3900 // that cascaded protections apply as soon as the changes
3901 // are visible.
3902
3903 # Get templates from templatelinks
3904 $id = $this->mTitle->getArticleID();
3905
3906 $tlTemplates = array();
3907
3908 $dbr = wfGetDB( DB_SLAVE );
3909 $res = $dbr->select( array( 'templatelinks' ),
3910 array( 'tl_namespace', 'tl_title' ),
3911 array( 'tl_from' => $id ),
3912 __METHOD__ );
3913
3914 global $wgContLang;
3915 foreach( $res as $row ) {
3916 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
3917 }
3918
3919 # Get templates from parser output.
3920 $poTemplates = array();
3921 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3922 foreach ( $templates as $dbk => $id ) {
3923 $poTemplates["$ns:$dbk"] = true;
3924 }
3925 }
3926
3927 # Get the diff
3928 # Note that we simulate array_diff_key in PHP <5.0.x
3929 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
3930
3931 if( count( $templates_diff ) > 0 ) {
3932 # Whee, link updates time.
3933 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
3934 $u->doUpdate();
3935 }
3936 }
3937
3938 /**
3939 * Update all the appropriate counts in the category table, given that
3940 * we've added the categories $added and deleted the categories $deleted.
3941 *
3942 * @param $added array The names of categories that were added
3943 * @param $deleted array The names of categories that were deleted
3944 * @return null
3945 */
3946 public function updateCategoryCounts( $added, $deleted ) {
3947 $ns = $this->mTitle->getNamespace();
3948 $dbw = wfGetDB( DB_MASTER );
3949
3950 # First make sure the rows exist. If one of the "deleted" ones didn't
3951 # exist, we might legitimately not create it, but it's simpler to just
3952 # create it and then give it a negative value, since the value is bogus
3953 # anyway.
3954 #
3955 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3956 $insertCats = array_merge( $added, $deleted );
3957 if( !$insertCats ) {
3958 # Okay, nothing to do
3959 return;
3960 }
3961 $insertRows = array();
3962 foreach( $insertCats as $cat ) {
3963 $insertRows[] = array( 'cat_title' => $cat );
3964 }
3965 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
3966
3967 $addFields = array( 'cat_pages = cat_pages + 1' );
3968 $removeFields = array( 'cat_pages = cat_pages - 1' );
3969 if( $ns == NS_CATEGORY ) {
3970 $addFields[] = 'cat_subcats = cat_subcats + 1';
3971 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3972 } elseif( $ns == NS_FILE ) {
3973 $addFields[] = 'cat_files = cat_files + 1';
3974 $removeFields[] = 'cat_files = cat_files - 1';
3975 }
3976
3977 if( $added ) {
3978 $dbw->update(
3979 'category',
3980 $addFields,
3981 array( 'cat_title' => $added ),
3982 __METHOD__
3983 );
3984 }
3985 if( $deleted ) {
3986 $dbw->update(
3987 'category',
3988 $removeFields,
3989 array( 'cat_title' => $deleted ),
3990 __METHOD__
3991 );
3992 }
3993 }
3994
3995 /** Lightweight method to get the parser output for a page, checking the parser cache
3996 * and so on. Doesn't consider most of the stuff that Article::view is forced to
3997 * consider, so it's not appropriate to use there. */
3998 function getParserOutput( $oldid = null ) {
3999 global $wgEnableParserCache, $wgUser, $wgOut;
4000
4001 // Should the parser cache be used?
4002 $useParserCache = $wgEnableParserCache &&
4003 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
4004 $this->exists() &&
4005 $oldid === null;
4006
4007 wfDebug( __METHOD__.': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
4008 if ( $wgUser->getOption( 'stubthreshold' ) ) {
4009 wfIncrStats( 'pcache_miss_stub' );
4010 }
4011
4012 $parserOutput = false;
4013 if ( $useParserCache ) {
4014 $parserOutput = ParserCache::singleton()->get( $this, $this->getParserOptions() );
4015 }
4016
4017 if ( $parserOutput === false ) {
4018 // Cache miss; parse and output it.
4019 $rev = Revision::newFromTitle( $this->getTitle(), $oldid );
4020
4021 return $this->getOutputFromWikitext( $rev->getText(), $useParserCache );
4022 } else {
4023 return $parserOutput;
4024 }
4025 }
4026 }